<commit_before>// Copyright 2018 Project Harbor Authors
//
// 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 api

import (
	"errors"
	"fmt"
	"github.com/goharbor/harbor/src/common"
	"github.com/goharbor/harbor/src/common/dao"
	"github.com/goharbor/harbor/src/common/models"
	"github.com/goharbor/harbor/src/common/rbac"
	"github.com/goharbor/harbor/src/common/rbac/project"
	"github.com/goharbor/harbor/src/common/utils"
	"github.com/goharbor/harbor/src/common/utils/log"
	"github.com/goharbor/harbor/src/core/config"
	"net/http"
	"regexp"
	"strconv"
)

// UserAPI handles request to /api/users/{}
type UserAPI struct {
	BaseController
	currentUserID    int
	userID           int
	SelfRegistration bool
	IsAdmin          bool
	AuthMode         string
	secretKey        string
}

type passwordReq struct {
	OldPassword string `json:"old_password"`
	NewPassword string `json:"new_password"`
}

type userSearch struct {
	UserID   int    `json:"user_id"`
	Username string `json:"username"`
}

type secretResp struct {
	Secret string `json:"secret"`
}

// Prepare validates the URL and parms
func (ua *UserAPI) Prepare() {
	ua.BaseController.Prepare()
	mode, err := config.AuthMode()
	if err != nil {
		log.Errorf("failed to get auth mode: %v", err)
		ua.SendInternalServerError(errors.New(""))
		return
	}

	ua.AuthMode = mode
	if mode == common.OIDCAuth {
		key, err := config.SecretKey()
		if err != nil {
			log.Errorf("failed to get secret key: %v", err)
			ua.SendInternalServerError(fmt.Errorf("failed to get secret key: %v", err))
			return
		}
		ua.secretKey = key
	}

	self, err := config.SelfRegistration()
	if err != nil {
		log.Errorf("failed to get self registration: %v", err)
		ua.SendInternalServerError(errors.New(""))
		return
	}

	ua.SelfRegistration = self

	if !ua.SecurityCtx.IsAuthenticated() {
		if ua.Ctx.Input.IsPost() {
			return
		}
		ua.SendUnAuthorizedError(errors.New("UnAuthorize"))
		return
	}

	user, err := dao.GetUser(models.User{
		Username: ua.SecurityCtx.GetUsername(),
	})
	if err != nil {
		ua.SendInternalServerError(fmt.Errorf("failed to get user %s: %v",
			ua.SecurityCtx.GetUsername(), err))
		return
	}

	ua.currentUserID = user.UserID
	id := ua.Ctx.Input.Param(":id")
	if id == "current" {<commit_msg>Check whether user is nil in Prepare() of users API (#7507)<commit_after>// Copyright 2018 Project Harbor Authors
//
// 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 api

import (
	"errors"
	"fmt"
	"github.com/goharbor/harbor/src/common"
	"github.com/goharbor/harbor/src/common/dao"
	"github.com/goharbor/harbor/src/common/models"
	"github.com/goharbor/harbor/src/common/rbac"
	"github.com/goharbor/harbor/src/common/rbac/project"
	"github.com/goharbor/harbor/src/common/utils"
	"github.com/goharbor/harbor/src/common/utils/log"
	"github.com/goharbor/harbor/src/core/config"
	"net/http"
	"regexp"
	"strconv"
)

// UserAPI handles request to /api/users/{}
type UserAPI struct {
	BaseController
	currentUserID    int
	userID           int
	SelfRegistration bool
	IsAdmin          bool
	AuthMode         string
	secretKey        string
}

type passwordReq struct {
	OldPassword string `json:"<PASSWORD>"`
	NewPassword string `json:"<PASSWORD>"`
}

type userSearch struct {
	UserID   int    `json:"user_id"`
	Username string `json:"username"`
}

type secretResp struct {
	Secret string `json:"secret"`
}

// Prepare validates the URL and parms
func (ua *UserAPI) Prepare() {
	ua.BaseController.Prepare()
	mode, err := config.AuthMode()
	if err != nil {
		log.Errorf("failed to get auth mode: %v", err)
		ua.SendInternalServerError(errors.New(""))
		return
	}

	ua.AuthMode = mode
	if mode == common.OIDCAuth {
		key, err := config.SecretKey()
		if err != nil {
			log.Errorf("failed to get secret key: %v", err)
			ua.SendInternalServerError(fmt.Errorf("failed to get secret key: %v", err))
			return
		}
		ua.secretKey = key
	}

	self, err := config.SelfRegistration()
	if err != nil {
		log.Errorf("failed to get self registration: %v", err)
		ua.SendInternalServerError(errors.New(""))
		return
	}

	ua.SelfRegistration = self

	if !ua.SecurityCtx.IsAuthenticated() {
		if ua.Ctx.Input.IsPost() {
			return
		}
		ua.SendUnAuthorizedError(errors.New("UnAuthorize"))
		return
	}

	user, err := dao.GetUser(models.User{
		Username: ua.SecurityCtx.GetUsername(),
	})
	if err != nil {
		ua.SendInternalServerError(fmt.Errorf("failed to get user %s: %v",
			ua.SecurityCtx.GetUsername(), err))
		return
	}

	if user == nil {
		log.Errorf("User with username %s does not exist in DB.", ua.SecurityCtx.GetUsername())
		ua.SendInternalServerError(fmt.Errorf("user %s does not exist in DB", ua.SecurityCtx.GetUsername()))
		return
	}

	ua.currentUserID = user.UserID
	id := ua.Ctx.Input.Param(":id")
	if id == "current" {
{'fraction_non_alphanumeric': 0.1281563472846766, 'fraction_numerical': 0.0034590107229332413, 'mean_word_length': 3.713121434392828, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1417782', 'n_tokens_mistral': 2023, 'n_tokens_neox': 1948, 'n_words': 526}