func()

in internal/auth/auth.go [128:202]


func (a *Auth) checkAuthenticationResponse(session *hostSession, w http.ResponseWriter, r *http.Request) {
	if !validateState(r, session) {
		// State is NOT ok
		logRequest(r).Warn("Authentication state did not match expected")

		httperrors.Serve401(w)
		return
	}

	redirectURI, ok := session.Values["uri"].(string)
	if !ok {
		logRequest(r).Error("Can not extract redirect uri from session")
		httperrors.Serve500(w)
		return
	}

	decryptedCode, err := a.DecryptCode(r.URL.Query().Get("code"),
		getRequestDomain(r, session.getNamespaceInPathFromSession()))
	if err != nil {
		logRequest(r).WithError(err).Error("failed to decrypt secure code")
		errortracking.CaptureErrWithReqAndStackTrace(err, r)
		httperrors.Serve500(w)
		return
	}

	// Fetch access token with authorization code
	token, err := a.fetchAccessToken(r.Context(), decryptedCode)
	if err != nil {
		if errors.Is(err, context.Canceled) {
			httperrors.Serve404(w)
			return
		}

		// Fetching token not OK
		logRequest(r).WithError(err).WithField(
			"redirect_uri", redirectURI,
		).Error(fetchAccessTokenErrMsg)
		errortracking.CaptureErrWithReqAndStackTrace(err, r, errortracking.WithField("redirect_uri", redirectURI))

		httperrors.Serve503(w)
		return
	}

	// Store access token
	session.Values["access_token"] = token.AccessToken

	// In final /auth call, updating session path with project prefix.
	// This will prevent leaking restricted and private projects/subgroups pages under the same top level group
	// https://gitlab.com/gitlab-org/gitlab-pages/-/issues/1088
	if feature.ProjectPrefixCookiePath.Enabled() && session.Values[projectPrefix] != nil {
		session.appendPath(session.Values[projectPrefix].(string))

		logRequest(r).WithField("Prefix Path", session.Values[projectPrefix].(string)).
			Info("Appending project prefix in session cookie path")

		// If project prefix is useful anywhere, we can avoid deleting it from session.
		delete(session.Values, projectPrefix)
	}

	err = session.Save(r, w)
	if err != nil {
		logRequest(r).WithError(err).Error(saveSessionErrMsg)
		errortracking.CaptureErrWithReqAndStackTrace(err, r)

		httperrors.Serve500(w)
		return
	}

	// Redirect back to requested URI
	logRequest(r).WithField(
		"redirect_uri", redirectURI,
	).Info("Authentication was successful, redirecting user back to requested page")

	http.Redirect(w, r, redirectURI, http.StatusFound)
}