Merge pull request #13 from ywk253100/golint_refactor

Golint refactor for model and dao
This commit is contained in:
reasonerjt 2016-02-26 16:10:23 +08:00
commit 415dc84560
33 changed files with 391 additions and 416 deletions

View File

@ -52,7 +52,7 @@ func (b *BaseAPI) ValidateUser() int {
b.CustomAbort(http.StatusUnauthorized, "")
}
userID := sessionUserID.(int)
u, err := dao.GetUser(models.User{UserId: userID})
u, err := dao.GetUser(models.User{UserID: userID})
if err != nil {
beego.Error("Error occurred in GetUser:", err)
b.CustomAbort(http.StatusInternalServerError, "Internal error.")

View File

@ -44,7 +44,7 @@ func (pma *ProjectMemberAPI) Prepare() {
pma.CustomAbort(http.StatusBadRequest, "invalid project Id")
return
}
p, err := dao.GetProjectById(pid)
p, err := dao.GetProjectByID(pid)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
@ -72,7 +72,7 @@ func (pma *ProjectMemberAPI) Prepare() {
}
func (pma *ProjectMemberAPI) Get() {
pid := pma.project.ProjectId
pid := pma.project.ProjectID
if !CheckProjectPermission(pma.currentUserID, pid) {
beego.Warning("Current user, user id :", pma.currentUserID, "does not have permission for project, id:", pid)
pma.RenderError(http.StatusForbidden, "")
@ -89,14 +89,14 @@ func (pma *ProjectMemberAPI) Get() {
}
pma.Data["json"] = userList
} else { //return detail of a member
roleList, err := dao.GetUserProjectRoles(models.User{UserId: pma.memberID}, pid)
roleList, err := dao.GetUserProjectRoles(models.User{UserID: pma.memberID}, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
//return empty role list to indicate if a user is not a member
result := make(map[string]interface{})
user, err := dao.GetUser(models.User{UserId: pma.memberID})
user, err := dao.GetUser(models.User{UserID: pma.memberID})
if err != nil {
beego.Error("Error occurred in GetUser:", err)
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
@ -110,8 +110,8 @@ func (pma *ProjectMemberAPI) Get() {
}
func (pma *ProjectMemberAPI) Post() {
pid := pma.project.ProjectId
userQuery := models.User{UserId: pma.currentUserID, RoleId: models.PROJECTADMIN}
pid := pma.project.ProjectID
userQuery := models.User{UserID: pma.currentUserID, RoleID: models.PROJECTADMIN}
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
@ -131,7 +131,7 @@ func (pma *ProjectMemberAPI) Post() {
pma.RenderError(http.StatusNotFound, "User does not exist")
return
}
rolelist, err = dao.GetUserProjectRoles(models.User{UserId: userID}, pid)
rolelist, err = dao.GetUserProjectRoles(models.User{UserID: userID}, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
pma.CustomAbort(http.StatusInternalServerError, "Internal error.")
@ -153,9 +153,9 @@ func (pma *ProjectMemberAPI) Post() {
}
func (pma *ProjectMemberAPI) Put() {
pid := pma.project.ProjectId
pid := pma.project.ProjectID
mid := pma.memberID
userQuery := models.User{UserId: pma.currentUserID, RoleId: models.PROJECTADMIN}
userQuery := models.User{UserID: pma.currentUserID, RoleID: models.PROJECTADMIN}
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
@ -168,7 +168,7 @@ func (pma *ProjectMemberAPI) Put() {
}
var req memberReq
pma.DecodeJSONReq(&req)
roleList, err := dao.GetUserProjectRoles(models.User{UserId: mid}, pid)
roleList, err := dao.GetUserProjectRoles(models.User{UserID: mid}, pid)
if len(roleList) == 0 {
beego.Warning("User is not in project, user id:", mid, ", project id:", pid)
pma.RenderError(http.StatusNotFound, "user not exist in project")
@ -194,9 +194,9 @@ func (pma *ProjectMemberAPI) Put() {
}
func (pma *ProjectMemberAPI) Delete() {
pid := pma.project.ProjectId
pid := pma.project.ProjectID
mid := pma.memberID
userQuery := models.User{UserId: pma.currentUserID, RoleId: models.PROJECTADMIN}
userQuery := models.User{UserID: pma.currentUserID, RoleID: models.PROJECTADMIN}
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if len(rolelist) == 0 {
beego.Warning("Current user, id:", pma.currentUserID, ", does not have project admin role for project, id:", pid)

View File

@ -84,10 +84,10 @@ func (p *ProjectAPI) Post() {
p.RenderError(http.StatusConflict, "")
return
}
project := models.Project{OwnerId: p.userID, Name: projectName, CreationTime: time.Now(), Public: public}
project := models.Project{OwnerID: p.userID, Name: projectName, CreationTime: time.Now(), Public: public}
err = dao.AddProject(project)
if err != nil {
beego.Error("Failed to add project, error: %v", err)
beego.Error("Failed to add project, error: ", err)
p.RenderError(http.StatusInternalServerError, "Failed to add project")
}
}
@ -107,7 +107,7 @@ func (p *ProjectAPI) Head() {
}
func (p *ProjectAPI) Get() {
queryProject := models.Project{UserId: p.userID}
queryProject := models.Project{UserID: p.userID}
projectName := p.GetString("project_name")
if len(projectName) > 0 {
queryProject.Name = "%" + projectName + "%"
@ -121,7 +121,7 @@ func (p *ProjectAPI) Get() {
p.CustomAbort(http.StatusInternalServerError, "Internal error.")
}
for i := 0; i < len(projectList); i++ {
if isProjectAdmin(p.userID, projectList[i].ProjectId) {
if isProjectAdmin(p.userID, projectList[i].ProjectID) {
projectList[i].Togglable = true
}
}
@ -167,7 +167,7 @@ func (p *ProjectAPI) FilterAccessLog() {
beginTime := time.Unix(filter.BeginTimestamp, 0)
endTime := time.Unix(filter.EndTimestamp, 0)
query := models.AccessLog{ProjectId: p.projectID, Username: "%" + username + "%", Keywords: keywords, BeginTime: beginTime, BeginTimestamp: filter.BeginTimestamp, EndTime: endTime, EndTimestamp: filter.EndTimestamp}
query := models.AccessLog{ProjectID: p.projectID, Username: "%" + username + "%", Keywords: keywords, BeginTime: beginTime, BeginTimestamp: filter.BeginTimestamp, EndTime: endTime, EndTimestamp: filter.EndTimestamp}
log.Printf("Query AccessLog: begin: %v, end: %v, keywords: %s", query.BeginTime, query.EndTime, query.Keywords)
@ -181,7 +181,7 @@ func (p *ProjectAPI) FilterAccessLog() {
}
func isProjectAdmin(userID int, pid int64) bool {
userQuery := models.User{UserId: userID, RoleId: models.PROJECTADMIN}
userQuery := models.User{UserID: userID, RoleID: models.PROJECTADMIN}
rolelist, err := dao.GetUserProjectRoles(userQuery, pid)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err, ", returning false")

View File

@ -40,7 +40,7 @@ type RepositoryAPI struct {
func (ra *RepositoryAPI) Prepare() {
userID, ok := ra.GetSession("userId").(int)
if !ok {
ra.userID = dao.NON_EXIST_USER_ID
ra.userID = dao.NonExistUserID
} else {
ra.userID = userID
}
@ -60,7 +60,7 @@ func (ra *RepositoryAPI) Get() {
ra.RenderError(http.StatusBadRequest, "Invalid project id")
return
}
p, err := dao.GetProjectById(projectID)
p, err := dao.GetProjectByID(projectID)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
ra.CustomAbort(http.StatusInternalServerError, "Internal error.")
@ -103,7 +103,7 @@ func (ra *RepositoryAPI) Get() {
}
type Tag struct {
Name string `json: "name"`
Name string `json:"name"`
Tags []string `json:"tags"`
}

View File

@ -39,7 +39,7 @@ type SearchResult struct {
func (n *SearchAPI) Get() {
userID, ok := n.GetSession("userId").(int)
if !ok {
userID = dao.NON_EXIST_USER_ID
userID = dao.NonExistUserID
}
keyword := n.GetString("q")
projects, err := dao.QueryRelevantProjects(userID)
@ -57,7 +57,7 @@ func (n *SearchAPI) Get() {
}
if match {
entry := make(map[string]interface{})
entry["id"] = p.ProjectId
entry["id"] = p.ProjectID
entry["name"] = p.Name
entry["public"] = p.Public
projectResult = append(projectResult, entry)
@ -93,7 +93,7 @@ func filterRepositories(repositories []string, projects []models.Project, keywor
entry := make(map[string]interface{})
entry["repository_name"] = r.Name
entry["project_name"] = projects[j].Name
entry["project_id"] = projects[j].ProjectId
entry["project_id"] = projects[j].ProjectID
entry["project_public"] = projects[j].Public
result = append(result, entry)
} else {

View File

@ -43,7 +43,7 @@ func (ua *UserAPI) Prepare() {
beego.Error("Invalid user id, error:", err)
ua.CustomAbort(http.StatusBadRequest, "Invalid user Id")
}
userQuery := models.User{UserId: ua.userID}
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
@ -83,7 +83,7 @@ func (ua *UserAPI) Get() {
ua.Data["json"] = userList
} else if ua.userID == ua.currentUserID || exist {
userQuery := models.User{UserId: ua.userID}
userQuery := models.User{UserID: ua.userID}
u, err := dao.GetUser(userQuery)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
@ -109,7 +109,7 @@ func (ua *UserAPI) Put() { //currently only for toggle admin, so no request body
ua.RenderError(http.StatusForbidden, "User does not have admin role")
return
}
userQuery := models.User{UserId: ua.userID}
userQuery := models.User{UserID: ua.userID}
dao.ToggleUserAdminRole(userQuery)
}

View File

@ -30,7 +30,7 @@ func CheckProjectPermission(userID int, projectID int64) bool {
if exist {
return true
}
roleList, err := dao.GetUserProjectRoles(models.User{UserId: userID}, projectID)
roleList, err := dao.GetUserProjectRoles(models.User{UserID: userID}, projectID)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
return false
@ -45,7 +45,7 @@ func CheckUserExists(name string) int {
return 0
}
if u != nil {
return u.UserId
return u.UserID
}
return 0
}

View File

@ -40,7 +40,7 @@ func Register(name string, authenticator Authenticator) {
func Login(m models.AuthModel) (*models.User, error) {
var authMode string = os.Getenv("AUTH_MODE")
var authMode = os.Getenv("AUTH_MODE")
if authMode == "" || m.Principal == "admin" {
authMode = "db_auth"
}

View File

@ -107,7 +107,7 @@ func (l *Auth) Authenticate(m models.AuthModel) (*models.User, error) {
if err != nil {
return nil, err
}
u.UserId = currentUser.UserId
u.UserID = currentUser.UserID
} else {
u.Password = "12345678AbC"
u.Comment = "registered from LDAP."
@ -115,7 +115,7 @@ func (l *Auth) Authenticate(m models.AuthModel) (*models.User, error) {
if err != nil {
return nil, err
}
u.UserId = int(userID)
u.UserID = int(userID)
}
return &u, nil
}

View File

@ -39,7 +39,7 @@ func (idc *ItemDetailController) Get() {
return
}
project, err := dao.GetProjectById(projectID)
project, err := dao.GetProjectByID(projectID)
if err != nil {
beego.Error("Error occurred in GetProjectById:", err)
@ -63,7 +63,7 @@ func (idc *ItemDetailController) Get() {
idc.Data["Username"] = idc.GetSession("username")
idc.Data["UserId"] = sessionUserID.(int)
roleList, err := dao.GetUserProjectRoles(models.User{UserId: sessionUserID.(int)}, projectID)
roleList, err := dao.GetUserProjectRoles(models.User{UserID: sessionUserID.(int)}, projectID)
if err != nil {
beego.Error("Error occurred in GetUserProjectRoles:", err)
idc.CustomAbort(http.StatusInternalServerError, "Internal error.")
@ -75,14 +75,14 @@ func (idc *ItemDetailController) Get() {
}
if len(roleList) > 0 {
idc.Data["RoleId"] = roleList[0].RoleId
idc.Data["RoleId"] = roleList[0].RoleID
}
}
idc.Data["ProjectId"] = project.ProjectId
idc.Data["ProjectId"] = project.ProjectID
idc.Data["ProjectName"] = project.Name
idc.Data["OwnerName"] = project.OwnerName
idc.Data["OwnerId"] = project.OwnerId
idc.Data["OwnerId"] = project.OwnerID
idc.Data["HarborRegUrl"] = os.Getenv("HARBOR_REG_URL")
idc.Data["RepoName"] = idc.GetString("repo_name")

View File

@ -54,7 +54,7 @@ func (c *CommonController) Login() {
c.CustomAbort(http.StatusUnauthorized, "")
}
c.SetSession("userId", user.UserId)
c.SetSession("userId", user.UserID)
c.SetSession("username", user.Username)
}

View File

@ -57,7 +57,7 @@ func (cc *CommonController) UpdatePassword() {
cc.CustomAbort(http.StatusBadRequest, "Old password is blank")
}
queryUser := models.User{UserId: sessionUserID.(int), Password: oldPassword}
queryUser := models.User{UserID: sessionUserID.(int), Password: oldPassword}
user, err := dao.CheckUserPassword(queryUser)
if err != nil {
beego.Error("Error occurred in CheckUserPassword:", err)
@ -71,7 +71,7 @@ func (cc *CommonController) UpdatePassword() {
password := cc.GetString("password")
if password != "" {
updateUser := models.User{UserId: sessionUserID.(int), Password: password, Salt: user.Salt}
updateUser := models.User{UserID: sessionUserID.(int), Password: password, Salt: user.Salt}
err = dao.ChangeUserPassword(updateUser, oldPassword)
if err != nil {
beego.Error("Error occurred in ChangeUserPassword:", err)
@ -163,8 +163,8 @@ func (cc *CommonController) SendEmail() {
cc.CustomAbort(http.StatusInternalServerError, "send_email_failed")
}
user := models.User{ResetUuid: uuid, Email: email}
dao.UpdateUserResetUuid(user)
user := models.User{ResetUUID: uuid, Email: email}
dao.UpdateUserResetUUID(user)
}
@ -183,7 +183,7 @@ func (rpc *ResetPasswordController) Get() {
return
}
queryUser := models.User{ResetUuid: resetUUID}
queryUser := models.User{ResetUUID: resetUUID}
user, err := dao.GetUser(queryUser)
if err != nil {
beego.Error("Error occurred in GetUser:", err)
@ -191,7 +191,7 @@ func (rpc *ResetPasswordController) Get() {
}
if user != nil {
rpc.Data["ResetUuid"] = user.ResetUuid
rpc.Data["ResetUuid"] = user.ResetUUID
rpc.ForwardTo("page_title_reset_password", "reset-password")
} else {
rpc.Redirect("/", http.StatusFound)
@ -205,7 +205,7 @@ func (cc *CommonController) ResetPassword() {
cc.CustomAbort(http.StatusBadRequest, "Reset uuid is blank.")
}
queryUser := models.User{ResetUuid: resetUUID}
queryUser := models.User{ResetUUID: resetUUID}
user, err := dao.GetUser(queryUser)
if err != nil {
beego.Error("Error occurred in GetUser:", err)

View File

@ -32,7 +32,7 @@ func AddAccessLog(accessLog models.AccessLog) error {
}
defer p.Close()
_, err = p.Exec(accessLog.UserId, accessLog.ProjectId, accessLog.RepoName, accessLog.Guid, accessLog.Operation)
_, err = p.Exec(accessLog.UserID, accessLog.ProjectID, accessLog.RepoName, accessLog.GUID, accessLog.Operation)
return err
}
@ -44,11 +44,11 @@ func GetAccessLogs(accessLog models.AccessLog) ([]models.AccessLog, error) {
from access_log a left join user u on a.user_id = u.user_id
where a.project_id = ? `
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, accessLog.ProjectId)
queryParam = append(queryParam, accessLog.ProjectID)
if accessLog.UserId != 0 {
if accessLog.UserID != 0 {
sql += ` and a.user_id = ? `
queryParam = append(queryParam, accessLog.UserId)
queryParam = append(queryParam, accessLog.UserID)
}
if accessLog.Operation != "" {
sql += ` and a.operation = ? `

View File

@ -22,12 +22,11 @@ import (
"strings"
"time"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
const NON_EXIST_USER_ID = 0
const NonExistUserID = 0
func isIllegalLength(s string, min int, max int) bool {
if min == -1 {
@ -74,26 +73,7 @@ func InitDB() {
password = os.Getenv("MYSQL_PWD")
}
var flag bool = true
if addr == "" {
beego.Error("Unset env of MYSQL_HOST")
flag = false
} else if port == "" {
beego.Error("Unset env of MYSQL_PORT_3306_TCP_PORT")
flag = false
} else if username == "" {
beego.Error("Unset env of MYSQL_USR")
flag = false
} else if password == "" {
beego.Error("Unset env of MYSQL_PWD")
flag = false
}
if !flag {
os.Exit(1)
}
db_str := username + ":" + password + "@tcp(" + addr + ":" + port + ")/registry"
dbStr := username + ":" + password + "@tcp(" + addr + ":" + port + ")/registry"
ch := make(chan int, 1)
go func() {
var err error
@ -114,7 +94,7 @@ func InitDB() {
case <-time.After(60 * time.Second):
panic("Failed to connect to DB after 60 seconds")
}
err := orm.RegisterDataBase("default", "mysql", db_str)
err := orm.RegisterDataBase("default", "mysql", dbStr)
if err != nil {
panic(err)
}

View File

@ -16,7 +16,6 @@ package dao
import (
"fmt"
// "fmt"
"log"
"os"
"testing"
@ -83,15 +82,15 @@ func clearUp(username string) {
o.Commit()
}
const USERNAME string = "Tester01"
const PROJECT_NAME string = "test_project"
const SYS_ADMIN int = 1
const PROJECT_ADMIN int = 2
const DEVELOPER int = 3
const GUEST int = 4
const username string = "Tester01"
const projectName string = "test_project"
const SysAdmin int = 1
const projectAdmin int = 2
const developer int = 3
const guest int = 4
const PUBLICITY_ON = 1
const PUBLICITY_OFF = 0
const publicityOn = 1
const publicityOff = 0
func TestMain(m *testing.M) {
@ -108,9 +107,6 @@ func TestMain(m *testing.M) {
log.Fatalf("environment variable DB_PORT is not set")
}
dbPassword := os.Getenv("DB_PWD")
if len(dbPassword) == 0 {
log.Fatalf("environment variable DB_PWD is not set")
}
fmt.Printf("DB_HOST: %s, DB_USR: %s, DB_PORT: %s, DB_PWD: %s\n", dbHost, dbUser, dbPort, dbPassword)
@ -120,7 +116,7 @@ func TestMain(m *testing.M) {
os.Setenv("MYSQL_PWD", dbPassword)
os.Setenv("AUTH_MODE", "db_auth")
InitDB()
clearUp(USERNAME)
clearUp(username)
os.Exit(m.Run())
}
@ -128,7 +124,7 @@ func TestMain(m *testing.M) {
func TestRegister(t *testing.T) {
user := models.User{
Username: USERNAME,
Username: username,
Email: "tester01@vmware.com",
Password: "Abc12345",
Realname: "tester01",
@ -142,15 +138,15 @@ func TestRegister(t *testing.T) {
//Check if user registered successfully.
queryUser := models.User{
Username: USERNAME,
Username: username,
}
newUser, err := GetUser(queryUser)
if err != nil {
t.Errorf("Error occurred in GetUser: %v", err)
}
if newUser.Username != USERNAME {
t.Errorf("Username does not match, expected: %s, actual: %s", USERNAME, newUser.Username)
if newUser.Username != username {
t.Errorf("Username does not match, expected: %s, actual: %s", username, newUser.Username)
}
if newUser.Email != "tester01@vmware.com" {
t.Errorf("Email does not match, expected: %s, actual: %s", "tester01@vmware.com", newUser.Email)
@ -161,12 +157,12 @@ func TestUserExists(t *testing.T) {
var exists bool
var err error
exists, err = UserExists(models.User{Username: USERNAME}, "username")
exists, err = UserExists(models.User{Username: username}, "username")
if err != nil {
t.Errorf("Error occurred in UserExists: %v", err)
}
if !exists {
t.Errorf("User %s was inserted but does not exist", USERNAME)
t.Errorf("User %s was inserted but does not exist", username)
}
exists, err = UserExists(models.User{Email: "tester01@vmware.com"}, "email")
@ -188,7 +184,7 @@ func TestUserExists(t *testing.T) {
func TestLoginByUserName(t *testing.T) {
userQuery := models.User{
Username: USERNAME,
Username: username,
Password: "Abc12345",
}
@ -200,8 +196,8 @@ func TestLoginByUserName(t *testing.T) {
t.Errorf("No found for user logined by username and password: %v", userQuery)
}
if loginUser.Username != USERNAME {
t.Errorf("User's username does not match after login, expected: %s, actual: %s", USERNAME, loginUser.Username)
if loginUser.Username != username {
t.Errorf("User's username does not match after login, expected: %s, actual: %s", username, loginUser.Username)
}
}
@ -219,8 +215,8 @@ func TestLoginByEmail(t *testing.T) {
if loginUser == nil {
t.Errorf("No found for user logined by email and password : %v", userQuery)
}
if loginUser.Username != USERNAME {
t.Errorf("User's username does not match after login, expected: %s, actual: %s", USERNAME, loginUser.Username)
if loginUser.Username != username {
t.Errorf("User's username does not match after login, expected: %s, actual: %s", username, loginUser.Username)
}
}
@ -228,7 +224,7 @@ var currentUser *models.User
func TestGetUser(t *testing.T) {
queryUser := models.User{
Username: USERNAME,
Username: username,
}
var err error
currentUser, err = GetUser(queryUser)
@ -251,12 +247,12 @@ func TestListUsers(t *testing.T) {
if len(users) != 1 {
t.Errorf("Expect one user in list, but the acutal length is %d, the list: %+v", len(users), users)
}
users2, err := ListUsers(models.User{Username: USERNAME})
users2, err := ListUsers(models.User{Username: username})
if len(users2) != 1 {
t.Errorf("Expect one user in list, but the acutal length is %d, the list: %+v", len(users), users)
}
if users2[0].Username != USERNAME {
t.Errorf("The username in result list does not match, expected: %s, actual: %s", USERNAME, users2[0].Username)
if users2[0].Username != username {
t.Errorf("The username in result list does not match, expected: %s, actual: %s", username, users2[0].Username)
}
}
@ -266,12 +262,12 @@ func TestResetUserPassword(t *testing.T) {
t.Errorf("Error occurred in GenerateRandomString: %v", err)
}
err = UpdateUserResetUuid(models.User{ResetUuid: uuid, Email: currentUser.Email})
err = UpdateUserResetUUID(models.User{ResetUUID: uuid, Email: currentUser.Email})
if err != nil {
t.Errorf("Error occurred in UpdateUserResetUuid: %v", err)
}
err = ResetUserPassword(models.User{UserId: currentUser.UserId, Password: "HarborTester12345", ResetUuid: uuid, Salt: currentUser.Salt})
err = ResetUserPassword(models.User{UserID: currentUser.UserID, Password: "HarborTester12345", ResetUUID: uuid, Salt: currentUser.Salt})
if err != nil {
t.Errorf("Error occurred in ResetUserPassword: %v", err)
}
@ -281,13 +277,13 @@ func TestResetUserPassword(t *testing.T) {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
if loginedUser.Username != USERNAME {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", USERNAME, loginedUser.Username)
if loginedUser.Username != username {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", username, loginedUser.Username)
}
}
func TestChangeUserPassword(t *testing.T) {
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewHarborTester12345", Salt: currentUser.Salt})
err := ChangeUserPassword(models.User{UserID: currentUser.UserID, Password: "NewHarborTester12345", Salt: currentUser.Salt})
if err != nil {
t.Errorf("Error occurred in ChangeUserPassword: %v", err)
}
@ -297,13 +293,13 @@ func TestChangeUserPassword(t *testing.T) {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
if loginedUser.Username != USERNAME {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", USERNAME, loginedUser.Username)
if loginedUser.Username != username {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", username, loginedUser.Username)
}
}
func TestChangeUserPasswordWithOldPassword(t *testing.T) {
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NewerHarborTester12345", Salt: currentUser.Salt}, "NewHarborTester12345")
err := ChangeUserPassword(models.User{UserID: currentUser.UserID, Password: "NewerHarborTester12345", Salt: currentUser.Salt}, "NewHarborTester12345")
if err != nil {
t.Errorf("Error occurred in ChangeUserPassword: %v", err)
}
@ -311,13 +307,13 @@ func TestChangeUserPasswordWithOldPassword(t *testing.T) {
if err != nil {
t.Errorf("Error occurred in LoginByDb: %v", err)
}
if loginedUser.Username != USERNAME {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", USERNAME, loginedUser.Username)
if loginedUser.Username != username {
t.Errorf("The username returned by Login does not match, expected: %s, acutal: %s", username, loginedUser.Username)
}
}
func TestChangeUserPasswordWithIncorrectOldPassword(t *testing.T) {
err := ChangeUserPassword(models.User{UserId: currentUser.UserId, Password: "NNewerHarborTester12345", Salt: currentUser.Salt}, "WrongNewerHarborTester12345")
err := ChangeUserPassword(models.User{UserID: currentUser.UserID, Password: "NNewerHarborTester12345", Salt: currentUser.Salt}, "WrongNewerHarborTester12345")
if err == nil {
t.Errorf("Error does not occurred due to old password is incorrect.")
}
@ -331,7 +327,7 @@ func TestChangeUserPasswordWithIncorrectOldPassword(t *testing.T) {
}
func TestQueryRelevantProjectsWhenNoProjectAdded(t *testing.T) {
projects, err := QueryRelevantProjects(currentUser.UserId)
projects, err := QueryRelevantProjects(currentUser.UserID)
if err != nil {
t.Errorf("Error occurred in QueryRelevantProjects: %v", err)
}
@ -346,8 +342,8 @@ func TestQueryRelevantProjectsWhenNoProjectAdded(t *testing.T) {
func TestAddProject(t *testing.T) {
project := models.Project{
OwnerId: currentUser.UserId,
Name: PROJECT_NAME,
OwnerID: currentUser.UserID,
Name: projectName,
CreationTime: time.Now(),
OwnerName: currentUser.Username,
}
@ -357,12 +353,12 @@ func TestAddProject(t *testing.T) {
t.Errorf("Error occurred in AddProject: %v", err)
}
newProject, err := GetProjectByName(PROJECT_NAME)
newProject, err := GetProjectByName(projectName)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
if newProject == nil {
t.Errorf("No project found queried by project name: %v", PROJECT_NAME)
t.Errorf("No project found queried by project name: %v", projectName)
}
}
@ -370,25 +366,25 @@ var currentProject *models.Project
func TestGetProject(t *testing.T) {
var err error
currentProject, err = GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(projectName)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
if currentProject == nil {
t.Errorf("No project found queried by project name: %v", PROJECT_NAME)
t.Errorf("No project found queried by project name: %v", projectName)
}
if currentProject.Name != PROJECT_NAME {
t.Errorf("Project name does not match, expected: %s, actual: %s", PROJECT_NAME, currentProject.Name)
if currentProject.Name != projectName {
t.Errorf("Project name does not match, expected: %s, actual: %s", projectName, currentProject.Name)
}
}
func getProjectRole(projectId int64) []models.Role {
func getProjectRole(projectID int64) []models.Role {
o := orm.NewOrm()
var r []models.Role
_, err := o.Raw(`select r.role_id, r.name
from project_role pr
left join role r on pr.role_id = r.role_id
where project_id = ?`, projectId).QueryRows(&r)
where project_id = ?`, projectID).QueryRows(&r)
if err != nil {
log.Printf("Error occurred in querying project_role: %v", err)
}
@ -396,12 +392,12 @@ func getProjectRole(projectId int64) []models.Role {
}
func TestCheckProjectRoles(t *testing.T) {
r := getProjectRole(currentProject.ProjectId)
r := getProjectRole(currentProject.ProjectID)
if len(r) != 3 {
t.Errorf("The length of project roles is not 3")
}
if r[1].RoleId != 3 {
t.Errorf("The role id does not match, expected: 3, acutal: %d", r[1].RoleId)
if r[1].RoleID != 3 {
t.Errorf("The role id does not match, expected: 3, acutal: %d", r[1].RoleID)
}
if r[1].Name != "developer" {
t.Errorf("The name of role id: 3 should be developer, actual:%s", r[1].Name)
@ -410,8 +406,8 @@ func TestCheckProjectRoles(t *testing.T) {
func TestGetAccessLog(t *testing.T) {
queryAccessLog := models.AccessLog{
UserId: currentUser.UserId,
ProjectId: currentProject.ProjectId,
UserID: currentUser.UserID,
ProjectID: currentProject.ProjectID,
}
accessLogs, err := GetAccessLogs(queryAccessLog)
if err != nil {
@ -420,20 +416,20 @@ func TestGetAccessLog(t *testing.T) {
if len(accessLogs) != 1 {
t.Errorf("The length of accesslog list should be 1, actual: %d", len(accessLogs))
}
if accessLogs[0].RepoName != PROJECT_NAME+"/" {
t.Errorf("The project name does not match, expected: %s, actual: %s", PROJECT_NAME+"/", accessLogs[0].RepoName)
if accessLogs[0].RepoName != projectName+"/" {
t.Errorf("The project name does not match, expected: %s, actual: %s", projectName+"/", accessLogs[0].RepoName)
}
}
func TestProjectExists(t *testing.T) {
var exists bool
var err error
exists, err = ProjectExists(currentProject.ProjectId)
exists, err = ProjectExists(currentProject.ProjectID)
if err != nil {
t.Errorf("Error occurred in ProjectExists: %v", err)
}
if !exists {
t.Errorf("The project with id: %d, does not exist", currentProject.ProjectId)
t.Errorf("The project with id: %d, does not exist", currentProject.ProjectID)
}
exists, err = ProjectExists(currentProject.Name)
if err != nil {
@ -445,8 +441,8 @@ func TestProjectExists(t *testing.T) {
}
func TestGetProjectById(t *testing.T) {
id := currentProject.ProjectId
p, err := GetProjectById(id)
id := currentProject.ProjectID
p, err := GetProjectByID(id)
if err != nil {
t.Errorf("Error in GetProjectById: %v, id: %d", err, id)
}
@ -456,7 +452,7 @@ func TestGetProjectById(t *testing.T) {
}
func TestGetUserByProject(t *testing.T) {
pid := currentProject.ProjectId
pid := currentProject.ProjectID
u1 := models.User{
Username: "%%Tester%%",
}
@ -465,14 +461,14 @@ func TestGetUserByProject(t *testing.T) {
}
users, err := GetUserByProject(pid, u1)
if err != nil {
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", u1)
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", err, pid, u1)
}
if len(users) != 1 {
t.Errorf("unexpected length of user list, expected: 1, the users list: %+v", users)
}
users, err = GetUserByProject(pid, u2)
if err != nil {
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", u2)
t.Errorf("Error happened in GetUserByProject: %v, project Id: %d, user: %+v", err, pid, u2)
}
if len(users) != 0 {
t.Errorf("unexpected length of user list, expected: 0, the users list: %+v", users)
@ -481,44 +477,44 @@ func TestGetUserByProject(t *testing.T) {
}
func TestToggleProjectPublicity(t *testing.T) {
err := ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_ON)
err := ToggleProjectPublicity(currentProject.ProjectID, publicityOn)
if err != nil {
t.Errorf("Error occurred in ToggleProjectPublicity: %v", err)
}
currentProject, err = GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(projectName)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
if currentProject.Public != PUBLICITY_ON {
t.Errorf("project, id: %d, its publicity is not on", currentProject.ProjectId)
if currentProject.Public != publicityOn {
t.Errorf("project, id: %d, its publicity is not on", currentProject.ProjectID)
}
err = ToggleProjectPublicity(currentProject.ProjectId, PUBLICITY_OFF)
err = ToggleProjectPublicity(currentProject.ProjectID, publicityOff)
if err != nil {
t.Errorf("Error occurred in ToggleProjectPublicity: %v", err)
}
currentProject, err = GetProjectByName(PROJECT_NAME)
currentProject, err = GetProjectByName(projectName)
if err != nil {
t.Errorf("Error occurred in GetProjectByName: %v", err)
}
if currentProject.Public != PUBLICITY_OFF {
t.Errorf("project, id: %d, its publicity is not off", currentProject.ProjectId)
if currentProject.Public != publicityOff {
t.Errorf("project, id: %d, its publicity is not off", currentProject.ProjectID)
}
}
func TestIsProjectPublic(t *testing.T) {
if isPublic := IsProjectPublic(PROJECT_NAME); isPublic {
t.Errorf("project, id: %d, its publicity is not false after turning off", currentProject.ProjectId)
if isPublic := IsProjectPublic(projectName); isPublic {
t.Errorf("project, id: %d, its publicity is not false after turning off", currentProject.ProjectID)
}
}
func TestQueryProject(t *testing.T) {
query1 := models.Project{
UserId: 1,
UserID: 1,
}
projects, err := QueryProject(query1)
if err != nil {
@ -538,7 +534,7 @@ func TestQueryProject(t *testing.T) {
t.Errorf("Expecting get 1 project, but actual: %d, the list: %+v", len(projects), projects)
}
query3 := models.Project{
UserId: 9,
UserID: 9,
}
projects, err = QueryProject(query3)
if err != nil {
@ -549,14 +545,14 @@ func TestQueryProject(t *testing.T) {
}
}
func getUserProjectRole(projectId int64, userId int) []models.Role {
func getUserProjectRole(projectID int64, userID int) []models.Role {
o := orm.NewOrm()
var r []models.Role
_, err := o.Raw(`select r.role_id, r.name
from user_project_role upr
left join project_role pr on upr.pr_id = pr.pr_id
left join role r on r.role_id = pr.role_id
where pr.project_id = ? and upr.user_id = ?`, projectId, userId).QueryRows(&r)
where pr.project_id = ? and upr.user_id = ?`, projectID, userID).QueryRows(&r)
if err != nil {
log.Fatalf("Error occurred in querying user_project_role: %v", err)
}
@ -565,28 +561,28 @@ func getUserProjectRole(projectId int64, userId int) []models.Role {
func TestGetUserProjectRoles(t *testing.T) {
user := *currentUser
r, err := GetUserProjectRoles(user, currentProject.ProjectId)
r, err := GetUserProjectRoles(user, currentProject.ProjectID)
if err != nil {
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectId)
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectID)
}
//Get the size of current user project role.
if len(r) != 1 {
t.Errorf("The user, id: %d, should only have one role in project, id: %d, but actual: %d", currentUser.UserId, currentProject.ProjectId, len(r))
t.Errorf("The user, id: %d, should only have one role in project, id: %d, but actual: %d", currentUser.UserID, currentProject.ProjectID, len(r))
}
if r[0].Name != "projectAdmin" {
t.Errorf("the expected rolename is: projectAdmin, actual: %s", r[0].Name)
}
user.RoleId = 1
user.RoleID = 1
r, err = GetUserProjectRoles(user, currentProject.ProjectId)
r, err = GetUserProjectRoles(user, currentProject.ProjectID)
if err != nil {
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectId)
t.Errorf("Error happened in GetUserProjectRole: %v, user: %+v, project Id: %d", err, user, currentProject.ProjectID)
}
//Get the size of current user project role.
if len(r) != 0 {
t.Errorf("The user, id: %d, should not have role id: 1 in project id: %d, actual role list: %v", currentUser.UserId, currentProject.ProjectId, r)
t.Errorf("The user, id: %d, should not have role id: 1 in project id: %d, actual role list: %v", currentUser.UserID, currentProject.ProjectID, r)
}
}
@ -601,43 +597,43 @@ func TestProjectPermission(t *testing.T) {
}
func TestQueryRelevantProjects(t *testing.T) {
projects, err := QueryRelevantProjects(currentUser.UserId)
projects, err := QueryRelevantProjects(currentUser.UserID)
if err != nil {
t.Errorf("Error occurred in QueryRelevantProjects: %v", err)
}
if len(projects) != 2 {
t.Errorf("Expected length of relevant projects is 2, but actual: %d, the projects: %+v", len(projects), projects)
}
if projects[1].Name != PROJECT_NAME {
t.Errorf("Expected project name in the list: %s, actual: %s", PROJECT_NAME, projects[1].Name)
if projects[1].Name != projectName {
t.Errorf("Expected project name in the list: %s, actual: %s", projectName, projects[1].Name)
}
}
func TestAssignUserProjectRole(t *testing.T) {
err := AddUserProjectRole(currentUser.UserId, currentProject.ProjectId, DEVELOPER)
err := AddUserProjectRole(currentUser.UserID, currentProject.ProjectID, developer)
if err != nil {
t.Errorf("Error occurred in AddUserProjectRole: %v", err)
}
r := getUserProjectRole(currentProject.ProjectId, currentUser.UserId)
r := getUserProjectRole(currentProject.ProjectID, currentUser.UserID)
//Get the size of current user project role info.
if len(r) != 2 {
t.Errorf("Expected length of role list is 2, actual: %d", len(r))
}
if r[1].RoleId != 3 {
t.Errorf("Expected role id of the second role in list is 3, actual: %d", r[1].RoleId)
if r[1].RoleID != 3 {
t.Errorf("Expected role id of the second role in list is 3, actual: %d", r[1].RoleID)
}
}
func TestDeleteUserProjectRole(t *testing.T) {
err := DeleteUserProjectRoles(currentUser.UserId, currentProject.ProjectId)
err := DeleteUserProjectRoles(currentUser.UserID, currentProject.ProjectID)
if err != nil {
t.Errorf("Error occurred in DeleteUserProjectRoles: %v", err)
}
r := getUserProjectRole(currentProject.ProjectId, currentUser.UserId)
r := getUserProjectRole(currentProject.ProjectID, currentUser.UserID)
//Get the size of current user project role.
if len(r) != 0 {
t.Errorf("Expected role list length is 0, actual: %d, role list: %+v", len(r), r)
@ -649,28 +645,28 @@ func TestToggleAdminRole(t *testing.T) {
if err != nil {
t.Errorf("Error in toggle ToggleUserAdmin role: %v, user: %+v", err, currentUser)
}
isAdmin, err := IsAdminRole(currentUser.UserId)
isAdmin, err := IsAdminRole(currentUser.UserID)
if err != nil {
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserId)
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserID)
}
if !isAdmin {
t.Errorf("User is not admin after toggled, user id: %d", currentUser.UserId)
t.Errorf("User is not admin after toggled, user id: %d", currentUser.UserID)
}
err = ToggleUserAdminRole(*currentUser)
if err != nil {
t.Errorf("Error in toggle ToggleUserAdmin role: %v, user: %+v", err, currentUser)
}
isAdmin, err = IsAdminRole(currentUser.UserId)
isAdmin, err = IsAdminRole(currentUser.UserID)
if err != nil {
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserId)
t.Errorf("Error in IsAdminRole: %v, user id: %d", err, currentUser.UserID)
}
if isAdmin {
t.Errorf("User is still admin after toggled, user id: %d", currentUser.UserId)
t.Errorf("User is still admin after toggled, user id: %d", currentUser.UserID)
}
}
func TestDeleteUser(t *testing.T) {
err := DeleteUser(currentUser.UserId)
err := DeleteUser(currentUser.UserID)
if err != nil {
t.Errorf("Error occurred in DeleteUser: %v", err)
}
@ -679,6 +675,6 @@ func TestDeleteUser(t *testing.T) {
t.Errorf("Error occurred in GetUser: %v", err)
}
if user != nil {
t.Error("user is not nil after deletion, user: %+v", user)
t.Errorf("user is not nil after deletion, user: %+v", user)
}
}

View File

@ -20,7 +20,7 @@ import (
"github.com/astaxie/beego/orm"
)
func GetUserByProject(projectId int64, queryUser models.User) ([]models.User, error) {
func GetUserByProject(projectID int64, queryUser models.User) ([]models.User, error) {
o := orm.NewOrm()
u := []models.User{}
sql := `select
@ -35,7 +35,7 @@ func GetUserByProject(projectId int64, queryUser models.User) ([]models.User, er
and pr.project_id = ? `
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, projectId)
queryParam = append(queryParam, projectID)
if queryUser.Username != "" {
sql += " and u.username like ? "

View File

@ -42,41 +42,41 @@ func AddProject(project models.Project) error {
return err
}
r, err := p.Exec(project.OwnerId, project.Name, project.Deleted, project.Public)
r, err := p.Exec(project.OwnerID, project.Name, project.Deleted, project.Public)
if err != nil {
return err
}
projectId, err := r.LastInsertId()
projectID, err := r.LastInsertId()
if err != nil {
return err
}
projectAdminRole := models.ProjectRole{ProjectId: projectId, RoleId: models.PROJECTADMIN}
projectAdminRole := models.ProjectRole{ProjectID: projectID, RoleID: models.PROJECTADMIN}
_, err = AddProjectRole(projectAdminRole)
if err != nil {
return err
}
projectDeveloperRole := models.ProjectRole{ProjectId: projectId, RoleId: models.DEVELOPER}
projectDeveloperRole := models.ProjectRole{ProjectID: projectID, RoleID: models.DEVELOPER}
_, err = AddProjectRole(projectDeveloperRole)
if err != nil {
return err
}
projectGuestRole := models.ProjectRole{ProjectId: projectId, RoleId: models.GUEST}
projectGuestRole := models.ProjectRole{ProjectID: projectID, RoleID: models.GUEST}
_, err = AddProjectRole(projectGuestRole)
if err != nil {
return err
}
//Add all project roles, after that when assigning a user to a project just update the upr table
err = AddUserProjectRole(project.OwnerId, projectId, models.PROJECTADMIN)
err = AddUserProjectRole(project.OwnerID, projectID, models.PROJECTADMIN)
if err != nil {
return err
}
accessLog := models.AccessLog{UserId: project.OwnerId, ProjectId: projectId, RepoName: project.Name + "/", Guid: "N/A", Operation: "create", OpTime: time.Now()}
accessLog := models.AccessLog{UserID: project.OwnerID, ProjectID: projectID, RepoName: project.Name + "/", GUID: "N/A", Operation: "create", OpTime: time.Now()}
err = AddAccessLog(accessLog)
return err
@ -111,10 +111,10 @@ func QueryProject(query models.Project) ([]models.Project, error) {
if query.Public == 1 {
sql += ` and p.public = ?`
queryParam = append(queryParam, query.Public)
} else if isAdmin, _ := IsAdminRole(query.UserId); isAdmin == false {
} else if isAdmin, _ := IsAdminRole(query.UserID); isAdmin == false {
sql += ` and (p.owner_id = ? or u.user_id = ?) `
queryParam = append(queryParam, query.UserId)
queryParam = append(queryParam, query.UserId)
queryParam = append(queryParam, query.UserID)
queryParam = append(queryParam, query.UserID)
}
if query.Name != "" {
@ -133,21 +133,21 @@ func QueryProject(query models.Project) ([]models.Project, error) {
return r, nil
}
func ProjectExists(nameOrId interface{}) (bool, error) {
func ProjectExists(nameOrID interface{}) (bool, error) {
o := orm.NewOrm()
type dummy struct{}
sql := `select project_id from project where deleted = 0 and `
switch nameOrId.(type) {
switch nameOrID.(type) {
case int64:
sql += `project_id = ?`
case string:
sql += `name = ?`
default:
return false, errors.New(fmt.Sprintf("Invalid nameOrId: %v", nameOrId))
return false, fmt.Errorf("Invalid nameOrId: %v", nameOrID)
}
var d []dummy
num, err := o.Raw(sql, nameOrId).QueryRows(&d)
num, err := o.Raw(sql, nameOrID).QueryRows(&d)
if err != nil {
return false, err
}
@ -155,13 +155,13 @@ func ProjectExists(nameOrId interface{}) (bool, error) {
}
func GetProjectById(projectId int64) (*models.Project, error) {
func GetProjectByID(projectID int64) (*models.Project, error) {
o := orm.NewOrm()
sql := `select p.project_id, p.name, u.username as owner_name, p.owner_id, p.creation_time, p.public
from project p left join user u on p.owner_id = u.user_id where p.deleted = 0 and p.project_id = ?`
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, projectId)
queryParam = append(queryParam, projectID)
p := []models.Project{}
count, err := o.Raw(sql, queryParam).QueryRows(&p)
@ -209,21 +209,21 @@ func GetPermission(username, projectName string) (string, error) {
}
}
func ToggleProjectPublicity(projectId int64, publicity int) error {
func ToggleProjectPublicity(projectID int64, publicity int) error {
o := orm.NewOrm()
sql := "update project set public = ? where project_id = ?"
_, err := o.Raw(sql, publicity, projectId).Exec()
_, err := o.Raw(sql, publicity, projectID).Exec()
return err
}
func QueryRelevantProjects(userId int) ([]models.Project, error) {
func QueryRelevantProjects(userID int) ([]models.Project, error) {
o := orm.NewOrm()
sql := `SELECT distinct p.project_id, p.name, p.public FROM registry.project p
left join project_role pr on p.project_id = pr.project_id
left join user_project_role upr on upr.pr_id = pr.pr_id
where upr.user_id = ? or p.public = 1 and p.deleted = 0`
var res []models.Project
_, err := o.Raw(sql, userId).QueryRows(&res)
_, err := o.Raw(sql, userID).QueryRows(&res)
if err != nil {
return nil, err
}

View File

@ -27,7 +27,7 @@ func AddProjectRole(projectRole models.ProjectRole) (int64, error) {
return 0, err
}
defer p.Close()
r, err := p.Exec(projectRole.ProjectId, projectRole.RoleId)
r, err := p.Exec(projectRole.ProjectID, projectRole.RoleID)
if err != nil {
return 0, err
}
@ -35,16 +35,16 @@ func AddProjectRole(projectRole models.ProjectRole) (int64, error) {
return id, err
}
func AddUserProjectRole(userId int, projectId int64, roleId int) error {
func AddUserProjectRole(userID int, projectID int64, roleID int) error {
o := orm.NewOrm()
var pr []models.ProjectRole
var prId int
var prID int
sql := `select pr.pr_id, pr.project_id, pr.role_id from project_role pr where pr.project_id = ? and pr.role_id = ?`
n, err := o.Raw(sql, projectId, roleId).QueryRows(&pr)
n, err := o.Raw(sql, projectID, roleID).QueryRows(&pr)
if err != nil {
return err
}
@ -55,7 +55,7 @@ func AddUserProjectRole(userId int, projectId int64, roleId int) error {
return err
}
defer p.Close()
r, err := p.Exec(projectId, roleId)
r, err := p.Exec(projectID, roleID)
if err != nil {
return err
}
@ -63,20 +63,20 @@ func AddUserProjectRole(userId int, projectId int64, roleId int) error {
if err != nil {
return err
}
prId = int(id)
prID = int(id)
} else if n > 0 {
prId = pr[0].PrId
prID = pr[0].PrID
}
p, err := o.Raw("insert into user_project_role (user_id, pr_id) values (?, ?)").Prepare()
if err != nil {
return err
}
defer p.Close()
_, err = p.Exec(userId, prId)
_, err = p.Exec(userID, prID)
return err
}
func DeleteUserProjectRoles(userId int, projectId int64) error {
func DeleteUserProjectRoles(userID int, projectID int64) error {
o := orm.NewOrm()
sql := `delete from user_project_role where user_id = ? and pr_id in
(select pr_id from project_role where project_id = ?)`
@ -84,6 +84,6 @@ func DeleteUserProjectRoles(userId int, projectId int64) error {
if err != nil {
return err
}
_, err = p.Exec(userId, projectId)
_, err = p.Exec(userID, projectID)
return err
}

View File

@ -48,12 +48,12 @@ func Register(user models.User) (int64, error) {
if err != nil {
return 0, err
}
userId, err := r.LastInsertId()
userID, err := r.LastInsertId()
if err != nil {
return 0, err
}
return userId, nil
return userID, nil
}
func validate(user models.User) error {

View File

@ -20,7 +20,7 @@ import (
"github.com/astaxie/beego/orm"
)
func GetUserProjectRoles(userQuery models.User, projectId int64) ([]models.Role, error) {
func GetUserProjectRoles(userQuery models.User, projectID int64) ([]models.Role, error) {
o := orm.NewOrm()
@ -32,15 +32,15 @@ func GetUserProjectRoles(userQuery models.User, projectId int64) ([]models.Role,
where u.deleted = 0
and u.user_id = ? `
queryParam := make([]interface{}, 1)
queryParam = append(queryParam, userQuery.UserId)
queryParam = append(queryParam, userQuery.UserID)
if projectId > 0 {
if projectID > 0 {
sql += ` and pr.project_id = ? `
queryParam = append(queryParam, projectId)
queryParam = append(queryParam, projectID)
}
if userQuery.RoleId > 0 {
if userQuery.RoleID > 0 {
sql += ` and r.role_id = ? `
queryParam = append(queryParam, userQuery.RoleId)
queryParam = append(queryParam, userQuery.RoleID)
}
var roleList []models.Role
@ -52,9 +52,9 @@ func GetUserProjectRoles(userQuery models.User, projectId int64) ([]models.Role,
return roleList, nil
}
func IsAdminRole(userId int) (bool, error) {
func IsAdminRole(userID int) (bool, error) {
//role_id == 1 means the user is system admin
userQuery := models.User{UserId: userId, RoleId: models.SYSADMIN}
userQuery := models.User{UserID: userID, RoleID: models.SYSADMIN}
adminRoleList, err := GetUserProjectRoles(userQuery, 0)
if err != nil {
return false, err

View File

@ -38,9 +38,9 @@ func GetUser(query models.User) (*models.User, error) {
from user u
where deleted = 0 `
queryParam := make([]interface{}, 1)
if query.UserId != 0 {
if query.UserID != 0 {
sql += ` and user_id = ? `
queryParam = append(queryParam, query.UserId)
queryParam = append(queryParam, query.UserID)
}
if query.Username != "" {
@ -48,9 +48,9 @@ func GetUser(query models.User) (*models.User, error) {
queryParam = append(queryParam, query.Username)
}
if query.ResetUuid != "" {
if query.ResetUUID != "" {
sql += ` and reset_uuid = ? `
queryParam = append(queryParam, query.ResetUuid)
queryParam = append(queryParam, query.ResetUUID)
}
var u []models.User
@ -108,13 +108,13 @@ func ListUsers(query models.User) ([]models.User, error) {
func ToggleUserAdminRole(u models.User) error {
projectRole := models.ProjectRole{PrId: 1} //admin project role
projectRole := models.ProjectRole{PrID: 1} //admin project role
o := orm.NewOrm()
var pr []models.ProjectRole
n, err := o.Raw(`select user_id from user_project_role where user_id = ? and pr_id = ? `, u.UserId, projectRole.PrId).QueryRows(&pr)
n, err := o.Raw(`select user_id from user_project_role where user_id = ? and pr_id = ? `, u.UserID, projectRole.PrID).QueryRows(&pr)
if err != nil {
return err
}
@ -131,7 +131,7 @@ func ToggleUserAdminRole(u models.User) error {
return err
}
defer p.Close()
_, err = p.Exec(u.UserId, projectRole.PrId)
_, err = p.Exec(u.UserID, projectRole.PrID)
return err
}
@ -142,9 +142,9 @@ func ChangeUserPassword(u models.User, oldPassword ...string) error {
var r sql.Result
if len(oldPassword) == 0 {
//In some cases, it may no need to check old password, just as Linux change password policies.
_, err = o.Raw(`update user set password=?, salt=? where user_id=?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserId).Exec()
_, err = o.Raw(`update user set password=?, salt=? where user_id=?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID).Exec()
} else if len(oldPassword) == 1 {
r, err = o.Raw(`update user set password=?, salt=? where user_id=? and password = ?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserId, utils.Encrypt(oldPassword[0], u.Salt)).Exec()
r, err = o.Raw(`update user set password=?, salt=? where user_id=? and password = ?`, utils.Encrypt(u.Password, u.Salt), u.Salt, u.UserID, utils.Encrypt(oldPassword[0], u.Salt)).Exec()
if err != nil {
return err
}
@ -163,7 +163,7 @@ func ChangeUserPassword(u models.User, oldPassword ...string) error {
func ResetUserPassword(u models.User) error {
o := orm.NewOrm()
r, err := o.Raw(`update user set password=?, reset_uuid=? where reset_uuid=?`, utils.Encrypt(u.Password, u.Salt), "", u.ResetUuid).Exec()
r, err := o.Raw(`update user set password=?, reset_uuid=? where reset_uuid=?`, utils.Encrypt(u.Password, u.Salt), "", u.ResetUUID).Exec()
if err != nil {
return err
}
@ -177,9 +177,9 @@ func ResetUserPassword(u models.User) error {
return err
}
func UpdateUserResetUuid(u models.User) error {
func UpdateUserResetUUID(u models.User) error {
o := orm.NewOrm()
_, err := o.Raw(`update user set reset_uuid=? where email=?`, u.ResetUuid, u.Email).Exec()
_, err := o.Raw(`update user set reset_uuid=? where email=?`, u.ResetUUID, u.Email).Exec()
return err
}
@ -199,10 +199,10 @@ func CheckUserPassword(query models.User) (*models.User, error) {
queryParam := make([]interface{}, 1)
if query.UserId != 0 {
if query.UserID != 0 {
sql += ` and password = ? and user_id = ?`
queryParam = append(queryParam, utils.Encrypt(query.Password, currentUser.Salt))
queryParam = append(queryParam, query.UserId)
queryParam = append(queryParam, query.UserID)
} else {
sql += ` and username = ? and password = ?`
queryParam = append(queryParam, currentUser.Username)
@ -223,8 +223,8 @@ func CheckUserPassword(query models.User) (*models.User, error) {
}
}
func DeleteUser(userId int) error {
func DeleteUser(userID int) error {
o := orm.NewOrm()
_, err := o.Raw(`update user set deleted = 1 where user_id = ?`, userId).Exec()
_, err := o.Raw(`update user set deleted = 1 where user_id = ?`, userID).Exec()
return err
}

View File

@ -34,7 +34,7 @@ const (
)
func updateInitPassword(userID int, password string) error {
queryUser := models.User{UserId: userID}
queryUser := models.User{UserID: userID}
user, err := dao.GetUser(queryUser)
if err != nil {
log.Println("Failed to get user, userID:", userID)
@ -42,7 +42,7 @@ func updateInitPassword(userID int, password string) error {
}
if user == nil {
log.Printf("User id: %d does not exist.", userID)
return fmt.Errorf("User id: %s does not exist.", userID)
return fmt.Errorf("User id: %d does not exist.", userID)
} else if user.Salt == "" {
salt, err := dao.GenerateRandomString()
if err != nil {

View File

@ -19,13 +19,13 @@ import (
)
type AccessLog struct {
LogId int
UserId int
ProjectId int64
RepoName string
Guid string
Operation string
OpTime time.Time
LogID int `orm:"column(log_id)" json:"LogId"`
UserID int `orm:"column(user_id)" json:"UserId"`
ProjectID int64 `orm:"column(project_id)" json:"ProjectId"`
RepoName string `orm:"column(repo_name)"`
GUID string `orm:"column(GUID)" json:"Guid"`
Operation string `orm:"column(operation)"`
OpTime time.Time `orm:"column(op_time)"`
Username string
Keywords string

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
@ -23,7 +23,7 @@ type Notification struct {
}
type Event struct {
Id string
ID string `json:"Id"`
TimeStamp time.Time
Action string
Target *Target
@ -35,7 +35,7 @@ type Target struct {
MediaType string
Digest string
Repository string
Url string
URL string `json:"Url"`
}
type Actor struct {
@ -43,7 +43,7 @@ type Actor struct {
}
type Request struct {
Id string
ID string `json:"Id"`
Method string
UserAgent string
}

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
@ -19,15 +19,15 @@ import (
)
type Project struct {
ProjectId int64
OwnerId int
Name string
CreationTime time.Time
ProjectID int64 `orm:"column(project_id)" json:"ProjectId"`
OwnerID int `orm:"column(owner_id)" json:"OwnerId"`
Name string `orm:"column(name)"`
CreationTime time.Time `orm:"column(creation_time)"`
CreationTimeStr string
Deleted int
UserId int
Deleted int `orm:"column(deleted)"`
UserID int `json:"UserId"`
OwnerName string
Public int
Public int `orm:"column(public)"`
//This field does not have correspondent column in DB, this is just for UI to disable button
Togglable bool
}

View File

@ -1,21 +1,21 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
type ProjectRole struct {
PrId int
ProjectId int64
RoleId int
PrID int `orm:"column(pr_id)" json:"PrId"`
ProjectID int64 `orm:"column(project_id)" json:"ProjectId"`
RoleID int `orm:"column(role_id)" json:"RoleId"`
}

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
@ -21,5 +21,5 @@ type V1Repo struct {
}
type Repo struct {
Repositories []string `json:repositories`
Repositories []string `json:"repositories"`
}

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
@ -19,14 +19,14 @@ import (
)
type RepoItem struct {
Id string `json:"Id"`
Parent string `json:"Parent"`
Created time.Time `json:"Created"`
CreatedStr string `json:"CreatedStr"`
DurationDays string `json:"Duration Days"`
Author string `json:"Author"`
Architecture string `json:"Architecture"`
Docker_version string `json:"Docker Version"`
Os string `json:"OS"`
ID string `json:"Id"`
Parent string `json:"Parent"`
Created time.Time `json:"Created"`
CreatedStr string `json:"CreatedStr"`
DurationDays string `json:"Duration Days"`
Author string `json:"Author"`
Architecture string `json:"Architecture"`
DockerVersion string `json:"Docker Version"`
Os string `json:"OS"`
//Size int `json:"Size"`
}

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
@ -22,7 +22,7 @@ const (
)
type Role struct {
RoleId int `json:"role_id"`
RoleCode string `json:"role_code"`
Name string `json:"role_name"`
RoleID int `json:"role_id" orm:"column(role_id)"`
RoleCode string `json:"role_code" orm:"column(role_code)"`
Name string `json:"role_name" orm:"column(name)"`
}

View File

@ -1,20 +1,20 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
type Tag struct {
Version string `json:version`
ImageId string `json:image_id`
Version string `json:"version"`
ImageID string `json:"image_id"`
}

View File

@ -1,31 +1,31 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
type User struct {
UserId int
Username string
Email string
Password string
Realname string
Comment string
Deleted int
UserID int `orm:"column(user_id)" json:"UserId"`
Username string `orm:"column(username)"`
Email string `orm:"column(email)"`
Password string `orm:"column(password)"`
Realname string `orm:"column(realname)"`
Comment string `orm:"column(comment)"`
Deleted int `orm:"column(deleted)"`
Rolename string
RoleId int
RoleID int `json:"RoleId"`
RoleList []Role
HasAdminRole int
ResetUuid string
Salt string
ResetUUID string `orm:"column(reset_uuid)" json:"ResetUuid"`
Salt string `orm:"column(salt)"`
}

View File

@ -1,21 +1,21 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package models
type UserProjectRole struct {
UprId int
UserId int
PrId int64
UprID int `orm:"column(upr_id)" json:"UprId"`
UserID int `orm:"column(user_id)" json:"UserId"`
PrID int64 `orm:"column(pr_id)" json:"PrId"`
}

View File

@ -1,16 +1,16 @@
/*
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Copyright (c) 2016 VMware, Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package utils
@ -27,9 +27,9 @@ import (
"github.com/astaxie/beego"
)
const SESSION_COOKIE = "beegosessionID"
const sessionCookie = "beegosessionID"
func BuildRegistryUrl(segments ...string) string {
func BuildRegistryURL(segments ...string) string {
registryURL := os.Getenv("REGISTRY_URL")
if registryURL == "" {
registryURL = "http://localhost:5000"
@ -45,8 +45,8 @@ func BuildRegistryUrl(segments ...string) string {
return url
}
func HttpGet(url, sessionId, username, password string) ([]byte, error) {
response, err := http.Get(url)
func HTTPGet(URL, sessionID, username, password string) ([]byte, error) {
response, err := http.Get(URL)
if err != nil {
return nil, err
}
@ -60,7 +60,7 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
} else if response.StatusCode == http.StatusUnauthorized {
authenticate := response.Header.Get("WWW-Authenticate")
str := strings.Split(authenticate, " ")[1]
beego.Trace("url: " + url)
beego.Trace("url: " + URL)
beego.Trace("Authentication Header: " + str)
var realm string
var service string
@ -72,7 +72,7 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
} else if strings.Contains(s, "service") {
service = s
} else if strings.Contains(s, "scope") {
strings.HasSuffix(url, "v2/_catalog")
strings.HasSuffix(URL, "v2/_catalog")
scope = s
}
}
@ -80,18 +80,18 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
service = strings.Split(service, "\"")[1]
scope = strings.Split(scope, "\"")[1]
authUrl := realm + "?service=" + service + "&scope=" + scope
authURL := realm + "?service=" + service + "&scope=" + scope
//skip certificate check if token service is https.
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
request, err := http.NewRequest("GET", authUrl, nil)
request, err := http.NewRequest("GET", authURL, nil)
if err != nil {
return nil, err
}
if len(sessionId) > 0 {
cookie := &http.Cookie{Name: SESSION_COOKIE, Value: sessionId, Path: "/"}
if len(sessionID) > 0 {
cookie := &http.Cookie{Name: sessionCookie, Value: sessionID, Path: "/"}
request.AddCookie(cookie)
} else {
request.SetBasicAuth(username, password)
@ -109,7 +109,7 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
if response.StatusCode == http.StatusOK {
tt := make(map[string]string)
json.Unmarshal(result, &tt)
request, err = http.NewRequest("GET", url, nil)
request, err = http.NewRequest("GET", URL, nil)
if err != nil {
return nil, err
}
@ -136,9 +136,8 @@ func HttpGet(url, sessionId, username, password string) ([]byte, error) {
defer response.Body.Close()
return result, nil
} else {
return nil, errors.New(string(result))
}
return nil, errors.New(string(result))
} else {
return nil, errors.New(string(result))
}