Merge branch 'pre_trustie_server' into trustie_server

This commit is contained in:
2023-04-07 17:23:17 +08:00
37 changed files with 340 additions and 68 deletions

View File

@@ -205,9 +205,10 @@ class AccountsController < ApplicationController
return
end
LimitForbidControl::UserLogin.new(@user).clear
successful_authentication(@user)
sync_pwd_to_gitea!(@user, {password: params[:password].to_s}) # TODO用户密码未同步
# session[:user_id] = @user.id
end

View File

@@ -0,0 +1,46 @@
class Api::V1::ProjectTopicsController < Api::V1::BaseController
def index
@project_topics = ProjectTopic
@project_topics = @project_topics.ransack(name_cont: params[:keyword]) if params[:keyword].present?
@project_topics = @project_topics.includes(:projects)
@project_topics = kaminary_select_paginate(@project_topics)
end
def create
ActiveRecord::Base.transaction do
@project = Project.find_by_id(create_params[:project_id])
return render_not_found unless @project.present?
return render_error("请输入项目搜索标签名称.") unless create_params[:name].present?
@project_topic = ProjectTopic.find_or_create_by!(name: create_params[:name].downcase)
@project_topic_ralate = @project_topic.project_topic_ralates.find_or_create_by!(project_id: create_params[:project_id])
if @project_topic.present? && @project_topic_ralate.present?
render_ok
else
render_error("项目关联搜索标签失败.")
end
end
end
def destroy
ActiveRecord::Base.transaction do
@project = Project.find_by_id(create_params[:project_id])
return render_not_found unless @project.present?
@project_topic = ProjectTopic.find_by_id(params[:id])
@project_topic_ralate = @project_topic.project_topic_ralates.find_by(project_id: @project.id)
if @project_topic_ralate.destroy!
render_ok
else
render_error("项目取消关联搜索标签失败.")
end
end
end
private
def create_params
params.permit(:project_id, :name)
end
end

View File

@@ -1,7 +1,7 @@
module Api::ProjectHelper
extend ActiveSupport::Concern
def load_project
def load_project
namespace = params[:owner]
repo = params[:repo]
@@ -14,7 +14,7 @@ module Api::ProjectHelper
else
logger.info "###########project not found"
@project = nil
render_not_found and return
tip_exception(404, '您访问的页面不存在或已被删除')
end
@project
end

View File

@@ -8,15 +8,20 @@ class InstallationsController < ApplicationController
end
def index
@install_bots = BotInstall.where(:installer_id => current_user.id)
@install_bots = BotInstall.where(bot_id: get_bot_id).group(:installer_id)
end
def show
@install_bot = BotInstall.find params[:id]
@install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
tip_exception "参数installer_id错误" if @install_bot.blank?
end
def repositories
@install_bots = BotInstall.where(:installer_id => current_user.id)
# 与github差异所以取安装用户和bot对应所有的仓库
# 必须使用access_tokens获取到bot的token才能查询
tip_exception "无效Token" if current_user.platform != "bot"
bot = Bot.find_by(uid: current_user.id)
@install_bots = BotInstall.where(bot_id: bot.id).where(installer_id: params[:id])
end
def update_secret
@@ -57,11 +62,13 @@ class InstallationsController < ApplicationController
@install_bot.update_attributes!(state: 0)
render_ok
end
def unsuspended
@install_bot = BotInstall.find params[:id]
@install_bot.update_attributes!(state: 1)
render_ok
end
def auth_active
begin
@bot = Bot.find params[:id]
@@ -86,7 +93,8 @@ class InstallationsController < ApplicationController
end
def access_tokens
@install_bot = BotInstall.find params[:id]
@install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
tip_exception "参数installer_id错误" if @install_bot.blank?
@bot = @install_bot.bot
@application = Doorkeeper::Application.find_by(uid: @bot.client_id, secret: @bot.client_secret)
tip_exception("该Bot未激活") if @application.blank?
@@ -101,5 +109,19 @@ class InstallationsController < ApplicationController
render_ok(token: @access_token.token)
end
private
def get_bot_id
header = request.authorization
pattern = /^Bearer /i
token = header.gsub(pattern, "")
decoded_token = JWT.decode token, nil, false
# 前面已验证token有效期和正确性
decoded_token[0]["iss"]
rescue JWT::DecodeError
Rails.logger.error "jwt token decode error:#{token}"
tip_exception("无效Token")
end
end

View File

@@ -34,7 +34,7 @@ class ProjectsController < ApplicationController
def index
scope = current_user.logged? ? Projects::ListQuery.call(params, current_user.id) : Projects::ListQuery.call(params)
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units))
@projects = kaminari_paginate(scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units, :project_topics))
# @projects = paginate scope.includes(:project_category, :project_language, :repository, :project_educoder, :owner, :project_units)
category_id = params[:category_id]
@@ -130,6 +130,13 @@ class ProjectsController < ApplicationController
# TODO:
# 临时特殊处理修改website、lesson_url操作方法
if project_params.has_key?("website")
if params[:project_topic_names].present? && params[:project_topic_names].is_a?(Array)
ProjectTopicRalate.where(project: @project).destroy_all
params[:project_topic_names].each do |name|
project_topic = ProjectTopic.find_or_create_by!(name: name.downcase)
project_topic.project_topic_ralates.find_or_create_by!(project: @project)
end
end
@project.update(project_params)
elsif project_params.has_key?("default_branch")
@project.update(project_params)

View File

@@ -241,9 +241,9 @@ class RepositoriesController < ApplicationController
def readme
if params[:filepath].present?
result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], current_user&.gitea_token)
result = Gitea::Repository::Readme::DirService.call(@owner.login, @repository.identifier, params[:filepath], params[:ref], @owner&.gitea_token)
else
result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], current_user&.gitea_token)
result = Gitea::Repository::Readme::GetService.call(@owner.login, @repository.identifier, params[:ref], @owner&.gitea_token)
end
@path = GiteaService.gitea_config[:domain]+"/#{@owner.login}/#{@repository.identifier}/raw/branch/#{params[:ref]}/"
@readme = result[:status] === :success ? result[:body] : nil

View File

@@ -4,7 +4,7 @@ class Projects::CreateForm < BaseForm
:blockchain, :blockchain_token_all, :blockchain_init_token
validates :user_id, :name, :repository_name, presence: true
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字字母下划线且不能以下划线开头和结尾" }
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "项目标识只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线开头和结尾" }
validates :name, length: { maximum: 50 }
validates :repository_name, length: { maximum: 100 }

View File

@@ -3,7 +3,7 @@ class Projects::MigrateForm < BaseForm
:project_language_id, :clone_addr, :private, :is_mirror, :auth_username, :auth_password, :owner
validates :user_id, :name, :repository_name, :clone_addr, presence: true
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字字母下划线且不能以下划线开头和结尾" }
validates :repository_name, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "项目标识只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线开头和结尾" }
validates :clone_addr, format: { with: CustomRegexp::URL_REGEX, multiline: true, message: "地址格式不正确" }
validates :name, length: { maximum: 50 }
validates :repository_name, length: { maximum: 100 }

View File

@@ -3,7 +3,7 @@ class Projects::UpdateForm < BaseForm
validates :name, presence: true
validates :name, length: { maximum: 50 }
validates :description, length: { maximum: 200 }
validates :identifier, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: "只能含有数字字母下划线不能以下划线开头和结尾" }
validates :identifier, format: { with: CustomRegexp::REPOSITORY_NAME_REGEX, multiline: true, message: '项目标识只能包含数字,字母,下划线(_),中划线(-),英文句号(.),必须以数字和字母开头,不能以下划线/中划线开头和结尾' }
validate do
check_project_category(project_category_id)

View File

@@ -25,7 +25,7 @@ module Gitea
def run
Contents::CreateForm.new(valid_params).validate!
result = Gitea::Repository::Entries::CreateService.call(token,
owner, @params[:identifier], @params[:filepath], file_params)
owner, @params[:identifier], file_path, file_params)
if result[:status] == :success
@result = result[:body]
@@ -50,9 +50,17 @@ module Gitea
@result = response
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
branch: @params[:branch],
new_branch: @params[:new_branch]
}

View File

@@ -24,7 +24,7 @@ module Gitea
def run
Contents::DeleteForm.new(valid_params).validate!
response = Gitea::Repository::Entries::DeleteService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::DeleteService.new(token, owner, @params[:identifier], file_path, file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@@ -45,9 +45,17 @@ module Gitea
end
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
sha: @params[:sha]
}
end

View File

@@ -24,7 +24,7 @@ module Gitea
def run
Contents::UpdateForm.new(valid_params).validate!
response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], @params[:filepath], file_params).call
response = Gitea::Repository::Entries::UpdateService.new(token, owner, @params[:identifier], file_path, file_params).call
render_result(response)
rescue Exception => exception
fail!(exception.message)
@@ -45,9 +45,25 @@ module Gitea
end
end
def file_path
if @params[:base64_filepath].present?
Base64.decode64(params[:base64_filepath])
else
@params[:filepath]
end
end
def from_file_path
if @params[:base64_from_path].present?
Base64.decode64(params[:base64_from_path])
else
@params[:from_path]
end
end
def valid_params
{
filepath: @params[:filepath],
filepath: file_path,
branch: @params[:branch],
new_branch: @params[:new_branch],
sha: @params[:sha]
@@ -59,7 +75,7 @@ module Gitea
branch: @params[:branch],
sha: @params[:sha],
new_branch: @params[:new_branch],
from_path: @params[:from_path],
from_path: from_file_path,
message: @params[:message],
content: Base64.encode64(@params[:content])
).compact

View File

@@ -10,6 +10,6 @@ module CustomRegexp
IP = /^((\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d{2}|2[0-4]\d|25[0-5])$/
URL_REGEX = /\A(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i
REPOSITORY_NAME_REGEX = /^(?!_)(?!.*?_$)[a-zA-Z0-9_-]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾
REPOSITORY_NAME_REGEX = /^[a-zA-Z0-9][a-zA-Z0-9\-\_\.]+$/ #只含有数字、字母、下划线不能以下划线开头和结尾
MD_REGEX = /^.+(\.[m|M][d|D])$/
end

View File

@@ -36,7 +36,7 @@ class Bot < ApplicationRecord
def self.decode_jwt_token(token)
decoded_token = JWT.decode token, nil, false
return [nil, "Token已过期"] if Time.now.to_i - 60 - decoded_token[0]["exp"].to_i > 0
return [nil, "Token已过期"] if Time.now.to_i - 10*60 - decoded_token[0]["exp"].to_i > 0
bot = Bot.find_by(id: decoded_token[0]["iss"])
return [nil, "Token不存在"] if bot.blank?
rsa_private = OpenSSL::PKey::RSA.new(bot.private_key)

View File

@@ -6,6 +6,7 @@ module Matchable
scope :with_project_language, ->(language_id) { where(project_language_id: language_id) unless language_id.blank? }
scope :with_project_type, ->(project_type) { where(project_type: project_type) if Project.project_types.include?(project_type) }
scope :by_name_or_identifier, ->(search) { where("name like :search or identifier LIKE :search", :search => "%#{search.split(" ").join('|')}%") unless search.blank? }
scope :with_project_topic, ->(topic_id) {joins(:project_topics).where(project_topics: {id: topic_id}) unless topic_id.blank?}
end
end

View File

@@ -93,9 +93,14 @@ module ProjectOperable
team_user.destroy! if team_user
end
# 安装bot后的权限
def is_install_bot?(user)
user.platform == "bot" && BotInstall.joins(:bot).where(bot: { uid: user.id }).where(store_id: self.id).exists?
end
def member?(user_id)
if owner.is_a?(User)
members.exists?(user_id: user_id)
members.exists?(user_id: user_id) || is_install_bot?(User.find_by(id: user_id))
elsif owner.is_a?(Organization)
members.exists?(user_id: user_id) || team_projects.joins(team: :team_users).where(team_users: {user_id: user_id}).present?
else

View File

@@ -126,6 +126,8 @@ class Project < ApplicationRecord
has_many :webhooks, class_name: "Gitea::Webhook", primary_key: :gpid, foreign_key: :repo_id
has_many :user_trace_tasks, dependent: :destroy
has_many :project_invite_links, dependent: :destroy
has_many :project_topic_ralates, dependent: :destroy
has_many :project_topics, through: :project_topic_ralates
after_create :incre_user_statistic, :incre_platform_statistic
after_save :check_project_members
before_save :set_invite_code, :reset_unmember_followed, :set_recommend_and_is_pinned, :reset_cache_data
@@ -380,7 +382,13 @@ class Project < ApplicationRecord
user = Owner.find_by_login namespace_path
user = User.new(login: namespace_path) if user.nil?
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
if identifier.end_with?('.json')
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
identifier = identifier.sub(/.*\K.json/, '')
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
else
project = user&.projects&.find_by(identifier: identifier) || Project.find_by(identifier: "#{namespace_path}/#{identifier}")
end
return nil if project.blank?
[project, user]

View File

@@ -0,0 +1,25 @@
# == Schema Information
#
# Table name: project_topics
#
# id :integer not null, primary key
# user_id :integer
# name :string(255)
# position :integer default("0")
# projects_count :integer default("0")
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_project_topics_on_user_id (user_id)
#
class ProjectTopic < ApplicationRecord
belongs_to :user, optional: true
has_many :project_topic_ralates, dependent: :destroy
has_many :projects, through: :project_topic_ralates
validates :name, uniqueness: { case_sensitive: false }
end

View File

@@ -0,0 +1,22 @@
# == Schema Information
#
# Table name: project_topic_ralates
#
# id :integer not null, primary key
# project_topic_id :integer
# project_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
# Indexes
#
# index_project_topic_ralates_on_project_id (project_id)
# index_project_topic_ralates_on_project_topic_id (project_topic_id)
#
class ProjectTopicRalate < ApplicationRecord
belongs_to :project_topic, counter_cache: :projects_count
belongs_to :project
end

View File

@@ -182,6 +182,7 @@ class User < Owner
has_many :assigned_issues, through: :issue_assigners, source: :issue
has_many :issue_participants, foreign_key: :participant_id
has_many :participant_issues, through: :issue_participants, source: :issue
has_many :project_topics
# Groups and active users
scope :active, lambda { where(status: [STATUS_ACTIVE, STATUS_EDIT_INFO]) }
scope :like, lambda { |keywords|

View File

@@ -67,7 +67,7 @@ class Projects::ListMyQuery < ApplicationQuery
keywords = params[:search].to_s.each_char.select { |c| c.bytes.first < 240 }.join('')
q = projects.ransack(name_or_identifier_cont: keywords)
scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users)
scope = q.result.includes(:project_category, :project_language,:owner, :repository, :has_pinned_users, :project_topics)
sort = Project.column_names.include?(params[:sort_by]) ? params[:sort_by] : "updated_on"
sort_direction = %w(desc asc).include?(params[:sort_direction]) ? params[:sort_direction] : "desc"

View File

@@ -3,7 +3,7 @@ class Projects::ListQuery < ApplicationQuery
attr_reader :params, :current_user_id
sort_columns :updated_on, :created_on, :forked_count, :praises_count, default_by: :updated_on, default_direction: :desc
sort_columns :updated_on, :created_on, :forked_count, :praises_count, default_by: :updated_on, default_direction: :desc, default_table: 'projects'
def initialize(params, current_user_id=nil)
@params = params
@@ -32,6 +32,7 @@ class Projects::ListQuery < ApplicationQuery
collection = by_project_type(collection)
collection = by_project_category(collection)
collection = by_project_language(collection)
collection = by_project_topic(collection)
collection
end
@@ -74,6 +75,10 @@ class Projects::ListQuery < ApplicationQuery
(params[:pinned].present? && params[:category_id].present?) ? items.pinned : items
end
def by_project_topic(items)
items.with_project_topic(params[:topic_id])
end
# 优化排序
def optimize_sorting(relations, sort_by)
if sort_by == "updated_on"

View File

@@ -0,0 +1,4 @@
json.total_count @project_topics.total_count
json.project_topics @project_topics.each do |topic|
json.(topic, :id, :name, :projects_count)
end

View File

@@ -3,7 +3,12 @@ json.type webhook["type"]
json.content_type webhook['config']['content_type']
json.http_method webhook['config']['http_method']
json.url webhook['config']['url']
json.events webhook['events']
event = webhook.events
if event["send_everything"]
json.events event["events"].keys.collect{|i| %w(pull_request issues).include?(i) ? i + "_only" : i}
else
json.events event["events"].select{|k, v| v}.keys.collect{|i| %w(pull_request issues).include?(i) ? i + "_only" : i}
end
json.active webhook['active']
json.branch_filter webhook['branch_filter']
json.created_at format_time(webhook['created_at'].to_time)

View File

@@ -2,10 +2,15 @@ json.status 0
json.message "success"
json.data do
json.array! @install_bots do |install_bot|
json.installation_id install_bot.id
json.extract! install_bot.bot, :id, :name
json.bot_id install_bot.bot.id
json.bot_name install_bot.bot.name
json.extract! install_bot, :id, :bot_id, :installer_id, :create_time, :update_time
json.bot_name install_bot&.bot&.name
json.account do
user = User.find_by(id: install_bot.installer_id)
if user.present?
json.partial! "api/v1/users/simple_user", locals: {user: user}
else
json.nil!
end
end
end
end

View File

@@ -1,5 +1,13 @@
json.partial! "commons/success"
json.extract! @install_bot, :id, :bot_id, :installer_id, :state, :create_time, :update_time
json.bot_name @install_bot.bot.name
json.extract! @install_bot, :id, :bot_id, :installer_id, :create_time, :update_time
json.bot_name @install_bot&.bot&.name
json.account do
user = User.find_by(id: @install_bot.installer_id)
if user.present?
json.partial! "api/v1/users/simple_user", locals: { user: user }
else
json.nil!
end
end

View File

@@ -50,3 +50,6 @@ json.language do
json.name project.project_language.name
end
end
json.topics project.project_topics.each do |topic|
json.(topic, :id, :name)
end

View File

@@ -48,4 +48,7 @@ json.projects @projects do |project|
json.name project.project_language.name
end
end
json.topics project.project_topics.each do |topic|
json.(topic, :id, :name)
end
end

View File

@@ -6,4 +6,7 @@ json.project_category_id @project.project_category_id
json.project_language_id @project.project_language_id
json.is_public @project.is_public
json.website @project.website
json.lesson_url @project.lesson_url
json.lesson_url @project.lesson_url
json.topics @project.project_topics.each do |topic|
json.(topic, :id, :name)
end

View File

@@ -5,7 +5,7 @@ json.create_time Time.at(@webhook.created_unix).strftime("%Y-%m-%d %H:%M:%S")
event = @webhook.events
json.branch_filter event["branch_filter"]
if event["send_everything"]
json.events event["events"].keys.collect{|i| i == "pull_request" ? i + "_only" : i}
json.events event["events"].keys.collect{|i| %w(pull_request issues).include?(i) ? i + "_only" : i}
else
json.events event["events"].select{|k, v| v}.keys.collect{|i| i == "pull_request" ? i + "_only" : i}
json.events event["events"].select{|k, v| v}.keys.collect{|i| %w(pull_request issues).include?(i) ? i + "_only" : i}
end

View File

@@ -21,6 +21,9 @@ json.mirror_url @project&.repository.remote_mirror_url
json.mirror @project&.repository.mirror_url.present?
json.type @project.numerical_for_project_type
json.open_devops @project.open_devops?
json.topics @project.project_topics.each do |topic|
json.(topic, :id, :name)
end
unless @project.common?
json.mirror_status @repository.mirror_status