Skip to content

The Unified and Autonomous Development Platform

feat: Service account for task automations (OD-2341)

Robin Shen4afcdf8fcfca
diff --git a/server-core/src/main/java/io/onedev/server/data/DefaultDataManager.java b/server-core/src/main/java/io/onedev/server/data/DefaultDataManager.java
index 2ebdcbcc67..32ce55ff80 100644
--- a/server-core/src/main/java/io/onedev/server/data/DefaultDataManager.java
+++ b/server-core/src/main/java/io/onedev/server/data/DefaultDataManager.java
@@ -2,6 +2,7 @@ package io.onedev.server.data;
import static com.google.common.base.Throwables.getStackTraceAsString;
import static io.onedev.server.model.User.PROP_NOTIFY_OWN_EVENTS;
+import static io.onedev.server.model.User.PROP_SERVICE_ACCOUNT;
import static io.onedev.server.model.support.administration.SystemSetting.PROP_CURL_LOCATION;
import static io.onedev.server.model.support.administration.SystemSetting.PROP_DISABLE_AUTO_UPDATE_CHECK;
import static io.onedev.server.model.support.administration.SystemSetting.PROP_GIT_LOCATION;
@@ -680,7 +681,7 @@ public class DefaultDataManager implements DataManager, Serializable {
if (validator.validate(bean).isEmpty()) {
createRoot(bean);
} else {
- manualConfigs.add(new ManualConfig("Create Administrator Account", null, bean, Sets.newHashSet(PROP_NOTIFY_OWN_EVENTS)) {
+ manualConfigs.add(new ManualConfig("Create Administrator Account", null, bean, Sets.newHashSet(PROP_SERVICE_ACCOUNT, PROP_NOTIFY_OWN_EVENTS)) {
@Override
public void complete() {
diff --git a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
index a55973c989..80b54e8139 100644
--- a/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
+++ b/server-core/src/main/java/io/onedev/server/data/migration/DataMigrator.java
@@ -7751,4 +7751,16 @@ public class DataMigrator {
}
}
+ private void migrate196(File dataDir, Stack<Integer> versions) {
+ for (File file : dataDir.listFiles()) {
+ if (file.getName().startsWith("Users.xml")) {
+ VersionedXmlDoc dom = VersionedXmlDoc.fromFile(file);
+ for (Element element : dom.getRootElement().elements()) {
+ element.addElement("serviceAccount").setText("false");
+ }
+ dom.writeToFile(file, false);
+ }
+ }
+ }
+
}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
index 614950b552..1c4c4f2262 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultIssueChangeManager.java
@@ -108,7 +108,7 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
@Transactional
@Override
public void create(IssueChange change, @Nullable String note) {
- create(change, note, true);
+ create(change, note, !change.getUser().isServiceAccount());
}
@Transactional
@@ -247,7 +247,7 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
@Transactional
@Override
public void addSchedule(Issue issue, Iteration iteration) {
- addSchedule(issue, iteration, true);
+ addSchedule(issue, iteration, !SecurityUtils.getUser().isServiceAccount());
}
protected void addSchedule(Issue issue, Iteration iteration, boolean sendNotifications) {
@@ -278,7 +278,7 @@ public class DefaultIssueChangeManager extends BaseEntityManager<IssueChange>
@Transactional
@Override
public void removeSchedule(Issue issue, Iteration iteration) {
- removeSchedule(issue, iteration, true);
+ removeSchedule(issue, iteration, !SecurityUtils.getUser().isServiceAccount());
}
@Transactional
diff --git a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultUserManager.java b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultUserManager.java
index 5c231dad62..8099b72222 100644
--- a/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultUserManager.java
+++ b/server-core/src/main/java/io/onedev/server/entitymanager/impl/DefaultUserManager.java
@@ -284,7 +284,10 @@ public class DefaultUserManager extends BaseEntityManager<User> implements UserM
public User findByPasswordResetCode(String passwordResetCode) {
var criteria = newCriteria();
criteria.add(Restrictions.eq("passwordResetCode", passwordResetCode));
- return find(criteria);
+ var user = find(criteria);
+ if (user != null && user.isServiceAccount())
+ throw new IllegalStateException();
+ return user;
}
@Override
@@ -367,10 +370,14 @@ public class DefaultUserManager extends BaseEntityManager<User> implements UserM
@Override
public User findByVerifiedEmailAddress(String emailAddressValue) {
EmailAddress emailAddress = emailAddressManager.findByValue(emailAddressValue);
- if (emailAddress != null && emailAddress.isVerified())
- return emailAddress.getOwner();
- else
+ if (emailAddress != null && emailAddress.isVerified()) {
+ var user = emailAddress.getOwner();
+ if (user.isServiceAccount())
+ throw new IllegalStateException();
+ return user;
+ } else {
return null;
+ }
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/event/project/issue/IssueChanged.java b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueChanged.java
index d3c8c9a396..97f6bd929e 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/issue/IssueChanged.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueChanged.java
@@ -26,7 +26,7 @@ public class IssueChanged extends IssueEvent implements CommitAware {
private final String comment;
public IssueChanged(IssueChange change, @Nullable String comment) {
- this(change, comment, true);
+ this(change, comment, !change.getUser().isServiceAccount());
}
public IssueChanged(IssueChange change, @Nullable String comment, boolean sendNotifications) {
diff --git a/server-core/src/main/java/io/onedev/server/event/project/issue/IssueEvent.java b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueEvent.java
index aed44fc102..714a48e6d7 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/issue/IssueEvent.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/issue/IssueEvent.java
@@ -22,7 +22,7 @@ public abstract class IssueEvent extends ProjectEvent {
private final boolean sendNotifications;
public IssueEvent(User user, Date date, Issue issue) {
- this(user, date, issue, true);
+ this(user, date, issue, !user.isServiceAccount());
}
public IssueEvent(User user, Date date, Issue issue, boolean sendNotifications) {
diff --git a/server-core/src/main/java/io/onedev/server/event/project/pack/PackEvent.java b/server-core/src/main/java/io/onedev/server/event/project/pack/PackEvent.java
index e4e71a206d..2e76530749 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/pack/PackEvent.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/pack/PackEvent.java
@@ -6,6 +6,7 @@ import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.PackManager;
import io.onedev.server.event.project.ProjectEvent;
import io.onedev.server.model.Pack;
+import io.onedev.server.model.User;
import io.onedev.server.web.UrlManager;
public abstract class PackEvent extends ProjectEvent {
@@ -14,8 +15,8 @@ public abstract class PackEvent extends ProjectEvent {
private final Long packId;
- public PackEvent(Date date, Pack pack) {
- super(null, date, pack.getProject());
+ public PackEvent(User user, Date date, Pack pack) {
+ super(user, date, pack.getProject());
packId = pack.getId();
}
diff --git a/server-core/src/main/java/io/onedev/server/event/project/pack/PackPublished.java b/server-core/src/main/java/io/onedev/server/event/project/pack/PackPublished.java
index 62c9a50626..9db25ccf7e 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/pack/PackPublished.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/pack/PackPublished.java
@@ -7,7 +7,7 @@ public class PackPublished extends PackEvent {
private static final long serialVersionUID = 1L;
public PackPublished(Pack pack) {
- super(pack.getPublishDate(), pack);
+ super(pack.getUser(), pack.getPublishDate(), pack);
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/event/project/pullrequest/PullRequestEvent.java b/server-core/src/main/java/io/onedev/server/event/project/pullrequest/PullRequestEvent.java
index 7dafe872c0..4fbc6d102b 100644
--- a/server-core/src/main/java/io/onedev/server/event/project/pullrequest/PullRequestEvent.java
+++ b/server-core/src/main/java/io/onedev/server/event/project/pullrequest/PullRequestEvent.java
@@ -2,6 +2,8 @@ package io.onedev.server.event.project.pullrequest;
import java.util.Date;
+import javax.annotation.Nullable;
+
import io.onedev.server.OneDev;
import io.onedev.server.entitymanager.PullRequestManager;
import io.onedev.server.web.UrlManager;
@@ -15,7 +17,7 @@ public abstract class PullRequestEvent extends ProjectEvent {
private final Long requestId;
- public PullRequestEvent(User user, Date date, PullRequest request) {
+ public PullRequestEvent(@Nullable User user, Date date, PullRequest request) {
super(user, date, request.getTargetProject());
requestId = request.getId();
}
diff --git a/server-core/src/main/java/io/onedev/server/model/User.java b/server-core/src/main/java/io/onedev/server/model/User.java
index a165a4e176..5003823ed0 100644
--- a/server-core/src/main/java/io/onedev/server/model/User.java
+++ b/server-core/src/main/java/io/onedev/server/model/User.java
@@ -39,6 +39,7 @@ import io.onedev.commons.utils.ExplicitException;
import io.onedev.server.OneDev;
import io.onedev.server.annotation.Editable;
import io.onedev.server.annotation.Password;
+import io.onedev.server.annotation.ShowCondition;
import io.onedev.server.annotation.UserName;
import io.onedev.server.entitymanager.EmailAddressManager;
import io.onedev.server.entitymanager.SettingManager;
@@ -51,6 +52,7 @@ import io.onedev.server.model.support.issue.NamedIssueQuery;
import io.onedev.server.model.support.pack.NamedPackQuery;
import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery;
import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.util.EditContext;
import io.onedev.server.util.facade.UserFacade;
import io.onedev.server.util.watch.QuerySubscriptionSupport;
import io.onedev.server.util.watch.QueryWatchSupport;
@@ -79,10 +81,14 @@ public class User extends AbstractEntity implements AuthenticationInfo {
public static final String PROP_FULL_NAME = "fullName";
+ public static final String PROP_SERVICE_ACCOUNT = "serviceAccount";
+
public static final String PROP_NOTIFY_OWN_EVENTS = "notifyOwnEvents";
private static ThreadLocal<Stack<User>> stack = ThreadLocal.withInitial(() -> new Stack<>());
+ private boolean serviceAccount;
+
@Column(unique=true, nullable=false)
private String name;
@@ -93,7 +99,7 @@ public class User extends AbstractEntity implements AuthenticationInfo {
private String password;
private String fullName;
-
+
private boolean notifyOwnEvents;
@JsonIgnore
@@ -496,6 +502,22 @@ public class User extends AbstractEntity implements AuthenticationInfo {
return SecurityUtils.asSubject(getPrincipals());
}
+ @Editable(order=50, name="Service Account", description = "Whether or not to create as a service account "
+ + "for task automation. Service account is not allowed to login via password, and will not generate "
+ + "notifications for its activities")
+ public boolean isServiceAccount() {
+ return serviceAccount;
+ }
+
+ public void setServiceAccount(boolean serviceAccount) {
+ this.serviceAccount = serviceAccount;
+ }
+
+ @SuppressWarnings("unused")
+ private static boolean isServiceAccountDisabled() {
+ return !(Boolean) EditContext.get().getInputValue(PROP_SERVICE_ACCOUNT);
+ }
+
@Editable(name="Login Name", order=100)
@UserName
@NotEmpty
@@ -513,6 +535,7 @@ public class User extends AbstractEntity implements AuthenticationInfo {
* time
*/
@Editable(order=150)
+ @ShowCondition("isServiceAccountDisabled")
@Password(needConfirm=true, autoComplete="new-password")
@NotEmpty
@Nullable
@@ -546,8 +569,9 @@ public class User extends AbstractEntity implements AuthenticationInfo {
public void setFullName(String fullName) {
this.fullName = fullName;
}
-
+
@Editable(order=400, name="Notify Own Events", description = "Whether or not to send notifications for events generated by yourself")
+ @ShowCondition("isServiceAccountDisabled")
public boolean isNotifyOwnEvents() {
return notifyOwnEvents;
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
index b6e6abfef3..0c154a3417 100644
--- a/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
@@ -112,7 +112,7 @@ public class BuildNotificationManager {
@Sessional
@Listen
public void on(BuildEvent event) {
- if (!(event instanceof BuildUpdated)) {
+ if (!(event instanceof BuildUpdated) && (event.getUser() == null || !event.getUser().isServiceAccount())) {
Project project = event.getProject();
Map<User, Collection<String>> subscribedQueryStrings = new HashMap<>();
for (BuildQueryPersonalization personalization: project.getBuildQueryPersonalizations()) {
diff --git a/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
index f42a70da15..347cb8888d 100644
--- a/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/ChannelNotificationManager.java
@@ -72,7 +72,7 @@ public abstract class ChannelNotificationManager<T extends ChannelNotificationSe
@Sessional
@Listen
public void on(PullRequestEvent event) {
- if (!event.isMinor()) {
+ if (!event.isMinor() && (event.getUser() == null || !event.getUser().isServiceAccount())) {
PullRequest request = event.getRequest();
User user = event.getUser();
@@ -91,23 +91,27 @@ public abstract class ChannelNotificationManager<T extends ChannelNotificationSe
@Sessional
@Listen
public void on(BuildEvent event) {
- Build build = event.getBuild();
-
- var status = StringUtils.capitalize(build.getStatus().toString().toLowerCase());
- String title;
- if (build.getVersion() != null)
- title = format("[Build %s] (%s: %s) %s", build.getReference(), build.getJobName(), build.getVersion(), status);
- else
- title = format("[Build %s] (%s) %s", build.getReference(), build.getJobName(), status);
- postIfApplicable(title, event);
+ if (event.getUser() == null || !event.getUser().isServiceAccount()) {
+ Build build = event.getBuild();
+
+ var status = StringUtils.capitalize(build.getStatus().toString().toLowerCase());
+ String title;
+ if (build.getVersion() != null)
+ title = format("[Build %s] (%s: %s) %s", build.getReference(), build.getJobName(), build.getVersion(), status);
+ else
+ title = format("[Build %s] (%s) %s", build.getReference(), build.getJobName(), status);
+ postIfApplicable(title, event);
+ }
}
@Sessional
@Listen
public void on(PackEvent event) {
- Pack pack = event.getPack();
- var title = format("[%s %s] Package published", pack.getType(), pack.getReference(true));
- postIfApplicable(title, event);
+ if (!event.getUser().isServiceAccount()) {
+ Pack pack = event.getPack();
+ var title = format("[%s %s] Package published", pack.getType(), pack.getReference(true));
+ postIfApplicable(title, event);
+ }
}
@Sessional
@@ -130,7 +134,7 @@ public abstract class ChannelNotificationManager<T extends ChannelNotificationSe
@Sessional
@Listen
public void on(CodeCommentEvent event) {
- if (!(event instanceof CodeCommentEdited)) {
+ if (!(event instanceof CodeCommentEdited) && !event.getUser().isServiceAccount()) {
CodeComment comment = event.getComment();
String title = format("[Code Comment %s:%s] %s %s",
diff --git a/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
index 6bf520c9da..1b1cf3dee6 100644
--- a/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
@@ -46,7 +46,7 @@ public class CodeCommentNotificationManager {
@Listen
public void on(CodeCommentEvent event) {
CodeComment comment = event.getComment();
- if (comment.getCompareContext().getPullRequest() == null) {
+ if (comment.getCompareContext().getPullRequest() == null && !event.getUser().isServiceAccount()) {
MarkdownText markdown = (MarkdownText) event.getCommentText();
Collection<User> notifyUsers = new HashSet<>();
diff --git a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
index 7f4417a0b8..8f66765c6b 100644
--- a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
@@ -185,7 +185,7 @@ public class IssueNotificationManager {
if (user != null) {
if (!user.isNotifyOwnEvents() || isNotified(notifiedEmailAddresses, user))
notifiedUsers.add(user);
- if (!user.isSystem())
+ if (!user.isSystem() && !user.isServiceAccount())
watchManager.watch(issue, user, true);
}
@@ -216,7 +216,8 @@ public class IssueNotificationManager {
}
for (User member: entry.getValue().getMembers()) {
- watchManager.watch(issue, member, true);
+ if (!member.isServiceAccount())
+ watchManager.watch(issue, member, true);
authorizationManager.authorize(issue, member);
}
@@ -244,7 +245,8 @@ public class IssueNotificationManager {
}
for (User each: entry.getValue()) {
- watchManager.watch(issue, each, true);
+ if (!each.isServiceAccount())
+ watchManager.watch(issue, each, true);
authorizationManager.authorize(issue, each);
}
notifiedUsers.addAll(entry.getValue());
@@ -256,7 +258,8 @@ public class IssueNotificationManager {
User mentionedUser = userManager.findByName(userName);
if (mentionedUser != null) {
mentionManager.mention(issue, mentionedUser);
- watchManager.watch(issue, mentionedUser, true);
+ if (!mentionedUser.isServiceAccount())
+ watchManager.watch(issue, mentionedUser, true);
authorizationManager.authorize(issue, mentionedUser);
if (!isNotified(notifiedEmailAddresses, mentionedUser)) {
String subject = String.format(
diff --git a/server-core/src/main/java/io/onedev/server/notification/PackNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/PackNotificationManager.java
index 1eabfb868f..9f67300648 100644
--- a/server-core/src/main/java/io/onedev/server/notification/PackNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/PackNotificationManager.java
@@ -88,90 +88,92 @@ public class PackNotificationManager {
@Sessional
@Listen
public void on(PackEvent event) {
- Project project = event.getProject();
- Map<User, Collection<String>> subscribedQueryStrings = new HashMap<>();
- for (PackQueryPersonalization personalization: project.getPackQueryPersonalizations()) {
- for (String name: personalization.getQuerySubscriptionSupport().getQuerySubscriptions()) {
- String commonName = NamedQuery.getCommonName(name);
- if (commonName != null) {
- fillSubscribedQueryStrings(subscribedQueryStrings, personalization.getUser(),
- NamedQuery.find(project.getNamedPackQueries(), commonName));
- }
- String personalName = NamedQuery.getPersonalName(name);
- if (personalName != null) {
- fillSubscribedQueryStrings(subscribedQueryStrings, personalization.getUser(),
- NamedQuery.find(personalization.getQueries(), personalName));
+ if (!event.getUser().isServiceAccount()) {
+ Project project = event.getProject();
+ Map<User, Collection<String>> subscribedQueryStrings = new HashMap<>();
+ for (PackQueryPersonalization personalization: project.getPackQueryPersonalizations()) {
+ for (String name: personalization.getQuerySubscriptionSupport().getQuerySubscriptions()) {
+ String commonName = NamedQuery.getCommonName(name);
+ if (commonName != null) {
+ fillSubscribedQueryStrings(subscribedQueryStrings, personalization.getUser(),
+ NamedQuery.find(project.getNamedPackQueries(), commonName));
+ }
+ String personalName = NamedQuery.getPersonalName(name);
+ if (personalName != null) {
+ fillSubscribedQueryStrings(subscribedQueryStrings, personalization.getUser(),
+ NamedQuery.find(personalization.getQueries(), personalName));
+ }
}
}
- }
-
- Pack pack = event.getPack();
- Collection<String> notifyEmails = new HashSet<>();
- for (Map.Entry<User, Collection<String>> entry: subscribedQueryStrings.entrySet()) {
- User user = entry.getKey();
- Permission permission = new ProjectPermission(pack.getProject(), new ReadPack());
- if (user.asSubject().isPermitted(permission)) {
- for (String queryString: entry.getValue()) {
- User.push(user);
- try {
- if (PackQuery.parse(event.getProject(), queryString, true).matches(pack)) {
- EmailAddress emailAddress = user.getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified())
- notifyEmails.add(emailAddress.getValue());
- break;
+
+ Pack pack = event.getPack();
+ Collection<String> notifyEmails = new HashSet<>();
+ for (Map.Entry<User, Collection<String>> entry: subscribedQueryStrings.entrySet()) {
+ User user = entry.getKey();
+ Permission permission = new ProjectPermission(pack.getProject(), new ReadPack());
+ if (user.asSubject().isPermitted(permission)) {
+ for (String queryString: entry.getValue()) {
+ User.push(user);
+ try {
+ if (PackQuery.parse(event.getProject(), queryString, true).matches(pack)) {
+ EmailAddress emailAddress = user.getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified())
+ notifyEmails.add(emailAddress.getValue());
+ break;
+ }
+ } catch (Exception e) {
+ String message = String.format("Error processing package subscription (user: %s, project: %s, package: %s, query: %s)",
+ user.getName(), pack.getProject().getPath(), pack.getType() + " " + pack.getReference(false), queryString);
+ logger.error(message, e);
+ } finally {
+ User.pop();
}
- } catch (Exception e) {
- String message = String.format("Error processing package subscription (user: %s, project: %s, package: %s, query: %s)",
- user.getName(), pack.getProject().getPath(), pack.getType() + " " + pack.getReference(false), queryString);
- logger.error(message, e);
- } finally {
- User.pop();
}
}
}
- }
-
- subscribedQueryStrings.clear();
- for (User user: userManager.query()) {
- for (String name: user.getPackQueryPersonalization().getQuerySubscriptionSupport().getQuerySubscriptions()) {
- String globalName = NamedQuery.getCommonName(name);
- if (globalName != null) {
- fillSubscribedQueryStrings(subscribedQueryStrings, user,
- NamedQuery.find(settingManager.getPackSetting().getNamedQueries(), globalName));
- }
- String personalName = NamedQuery.getPersonalName(name);
- if (personalName != null) {
- fillSubscribedQueryStrings(subscribedQueryStrings, user,
- NamedQuery.find(user.getPackQueryPersonalization().getQueries(), personalName));
+
+ subscribedQueryStrings.clear();
+ for (User user: userManager.query()) {
+ for (String name: user.getPackQueryPersonalization().getQuerySubscriptionSupport().getQuerySubscriptions()) {
+ String globalName = NamedQuery.getCommonName(name);
+ if (globalName != null) {
+ fillSubscribedQueryStrings(subscribedQueryStrings, user,
+ NamedQuery.find(settingManager.getPackSetting().getNamedQueries(), globalName));
+ }
+ String personalName = NamedQuery.getPersonalName(name);
+ if (personalName != null) {
+ fillSubscribedQueryStrings(subscribedQueryStrings, user,
+ NamedQuery.find(user.getPackQueryPersonalization().getQueries(), personalName));
+ }
}
}
- }
-
- for (Map.Entry<User, Collection<String>> entry: subscribedQueryStrings.entrySet()) {
- User user = entry.getKey();
- Permission permission = new ProjectPermission(pack.getProject(), new ReadPack());
- if (user.asSubject().isPermitted(permission)) {
- for (String queryString: entry.getValue()) {
- User.push(user);
- try {
- if (PackQuery.parse(null, queryString, true).matches(pack)) {
- EmailAddress emailAddress = user.getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified())
- notifyEmails.add(emailAddress.getValue());
- break;
+
+ for (Map.Entry<User, Collection<String>> entry: subscribedQueryStrings.entrySet()) {
+ User user = entry.getKey();
+ Permission permission = new ProjectPermission(pack.getProject(), new ReadPack());
+ if (user.asSubject().isPermitted(permission)) {
+ for (String queryString: entry.getValue()) {
+ User.push(user);
+ try {
+ if (PackQuery.parse(null, queryString, true).matches(pack)) {
+ EmailAddress emailAddress = user.getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified())
+ notifyEmails.add(emailAddress.getValue());
+ break;
+ }
+ } catch (Exception e) {
+ String message = String.format("Error processing package subscription (user: %s, project: %s, package: %s, query: %s)",
+ user.getName(), pack.getProject().getPath(), pack.getType() + " " + pack.getReference(false), queryString);
+ logger.error(message, e);
+ } finally {
+ User.pop();
}
- } catch (Exception e) {
- String message = String.format("Error processing package subscription (user: %s, project: %s, package: %s, query: %s)",
- user.getName(), pack.getProject().getPath(), pack.getType() + " " + pack.getReference(false), queryString);
- logger.error(message, e);
- } finally {
- User.pop();
}
}
}
+
+ notify(event, notifyEmails);
}
-
- notify(event, notifyEmails);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
index a8b6b19969..51e37b6719 100644
--- a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
@@ -69,264 +69,269 @@ public class PullRequestNotificationManager {
@Transactional
@Listen
public void on(PullRequestEvent event) {
- PullRequest request = event.getRequest();
- User user = event.getUser();
-
- String url = event.getUrl();
-
- for (Map.Entry<User, Boolean> entry : new QueryWatchBuilder<PullRequest>() {
-
- @Override
- protected PullRequest getEntity() {
- return request;
- }
-
- @Override
- protected Collection<? extends QueryPersonalization<?>> getQueryPersonalizations() {
- return request.getTargetProject().getPullRequestQueryPersonalizations();
- }
-
- @Override
- protected EntityQuery<PullRequest> parse(String queryString) {
- return PullRequestQuery.parse(request.getTargetProject(), queryString, true);
- }
-
- @Override
- protected Collection<? extends NamedQuery> getNamedQueries() {
- return request.getTargetProject().getNamedPullRequestQueries();
- }
-
- }.getWatches().entrySet()) {
- watchManager.watch(request, entry.getKey(), entry.getValue());
- }
-
- for (Map.Entry<User, Boolean> entry : new QueryWatchBuilder<PullRequest>() {
-
- @Override
- protected PullRequest getEntity() {
- return request;
- }
-
- @Override
- protected Collection<? extends QueryPersonalization<?>> getQueryPersonalizations() {
- return userManager.query().stream().map(it -> it.getPullRequestQueryPersonalization()).collect(Collectors.toList());
- }
-
- @Override
- protected EntityQuery<PullRequest> parse(String queryString) {
- return PullRequestQuery.parse(null, queryString, true);
+ if (event.getUser() == null || !event.getUser().isServiceAccount()) {
+ PullRequest request = event.getRequest();
+ User user = event.getUser();
+
+ String url = event.getUrl();
+
+ for (Map.Entry<User, Boolean> entry : new QueryWatchBuilder<PullRequest>() {
+
+ @Override
+ protected PullRequest getEntity() {
+ return request;
+ }
+
+ @Override
+ protected Collection<? extends QueryPersonalization<?>> getQueryPersonalizations() {
+ return request.getTargetProject().getPullRequestQueryPersonalizations();
+ }
+
+ @Override
+ protected EntityQuery<PullRequest> parse(String queryString) {
+ return PullRequestQuery.parse(request.getTargetProject(), queryString, true);
+ }
+
+ @Override
+ protected Collection<? extends NamedQuery> getNamedQueries() {
+ return request.getTargetProject().getNamedPullRequestQueries();
+ }
+
+ }.getWatches().entrySet()) {
+ watchManager.watch(request, entry.getKey(), entry.getValue());
}
-
- @Override
- protected Collection<? extends NamedQuery> getNamedQueries() {
- return settingManager.getPullRequestSetting().getNamedQueries();
+
+ for (Map.Entry<User, Boolean> entry : new QueryWatchBuilder<PullRequest>() {
+
+ @Override
+ protected PullRequest getEntity() {
+ return request;
+ }
+
+ @Override
+ protected Collection<? extends QueryPersonalization<?>> getQueryPersonalizations() {
+ return userManager.query().stream().map(it -> it.getPullRequestQueryPersonalization()).collect(Collectors.toList());
+ }
+
+ @Override
+ protected EntityQuery<PullRequest> parse(String queryString) {
+ return PullRequestQuery.parse(null, queryString, true);
+ }
+
+ @Override
+ protected Collection<? extends NamedQuery> getNamedQueries() {
+ return settingManager.getPullRequestSetting().getNamedQueries();
+ }
+
+ }.getWatches().entrySet()) {
+ watchManager.watch(request, entry.getKey(), entry.getValue());
}
-
- }.getWatches().entrySet()) {
- watchManager.watch(request, entry.getKey(), entry.getValue());
- }
-
- Collection<String> notifiedEmailAddresses;
- if (event instanceof PullRequestCommentCreated)
- notifiedEmailAddresses = ((PullRequestCommentCreated) event).getNotifiedEmailAddresses();
- else
- notifiedEmailAddresses = new HashSet<>();
-
- Collection<User> notifiedUsers = Sets.newHashSet();
- if (user != null) {
- if (!user.isNotifyOwnEvents() || isNotified(notifiedEmailAddresses, user))
- notifiedUsers.add(user);
- if (!user.isSystem())
- watchManager.watch(request, user, true);
- }
-
- User committer = null;
- if (event instanceof PullRequestUpdated) {
- PullRequestUpdated pullRequestUpdated = (PullRequestUpdated) event;
- Collection<User> committers = pullRequestUpdated.getCommitters();
- if (committers.size() == 1) {
- committer = committers.iterator().next();
- notifiedUsers.add(committer);
+
+ Collection<String> notifiedEmailAddresses;
+ if (event instanceof PullRequestCommentCreated)
+ notifiedEmailAddresses = ((PullRequestCommentCreated) event).getNotifiedEmailAddresses();
+ else
+ notifiedEmailAddresses = new HashSet<>();
+
+ Collection<User> notifiedUsers = Sets.newHashSet();
+ if (user != null) {
+ if (!user.isNotifyOwnEvents() || isNotified(notifiedEmailAddresses, user))
+ notifiedUsers.add(user);
+ if (!user.isSystem() && !user.isServiceAccount())
+ watchManager.watch(request, user, true);
}
- for (User each : committers) {
- if (!each.isSystem())
- watchManager.watch(request, each, true);
+
+ User committer = null;
+ if (event instanceof PullRequestUpdated) {
+ PullRequestUpdated pullRequestUpdated = (PullRequestUpdated) event;
+ Collection<User> committers = pullRequestUpdated.getCommitters();
+ if (committers.size() == 1) {
+ committer = committers.iterator().next();
+ notifiedUsers.add(committer);
+ }
+ for (User each : committers) {
+ if (!each.isSystem() && !each.isServiceAccount())
+ watchManager.watch(request, each, true);
+ }
}
- }
-
- String senderName;
- String summary;
- if (user != null) {
- senderName = user.getDisplayName();
- summary = user.getDisplayName() + " " + event.getActivity();
- } else if (committer != null) {
- senderName = null;
- summary = committer.getDisplayName() + " " + event.getActivity();
- } else {
- senderName = null;
- summary = StringUtils.capitalize(event.getActivity());
- }
-
- var emojis = Emojis.getInstance();
- String replyAddress = mailManager.getReplyAddress(request);
- boolean replyable = replyAddress != null;
-
- Set<User> reviewers = new HashSet<>();
- Set<User> assignees = new HashSet<>();
- if (event instanceof PullRequestOpened) {
- for (PullRequestReview review : request.getReviews()) {
- if (review.getStatus() == Status.PENDING)
- reviewers.add(review.getUser());
+
+ String senderName;
+ String summary;
+ if (user != null) {
+ senderName = user.getDisplayName();
+ summary = user.getDisplayName() + " " + event.getActivity();
+ } else if (committer != null) {
+ senderName = null;
+ summary = committer.getDisplayName() + " " + event.getActivity();
+ } else {
+ senderName = null;
+ summary = StringUtils.capitalize(event.getActivity());
}
- for (PullRequestAssignment assignment : request.getAssignments())
- assignees.add(assignment.getUser());
- } else if (event instanceof PullRequestChanged) {
- PullRequestChanged changeEvent = (PullRequestChanged) event;
- PullRequestChangeData changeData = changeEvent.getChange().getData();
- if ((changeData instanceof PullRequestApproveData
- || changeData instanceof PullRequestRequestedForChangesData
- || changeData instanceof PullRequestDiscardData)
- && request.getSubmitter() != null && !notifiedUsers.contains(request.getSubmitter())) {
- String subject = String.format(
- "[Pull Request %s] (%s) %s",
- request.getReference(),
- WordUtils.capitalize(changeData.getActivity()),
- emojis.apply(request.getTitle()));
- String threadingReferences = String.format("<%s-%s@onedev>",
- changeData.getActivity().replace(' ', '-'), request.getUUID());
- EmailAddress emailAddress = request.getSubmitter().getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified()) {
- mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
- Lists.newArrayList(), Lists.newArrayList(), subject,
- getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, null),
- getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
- replyAddress, senderName, threadingReferences);
+
+ var emojis = Emojis.getInstance();
+ String replyAddress = mailManager.getReplyAddress(request);
+ boolean replyable = replyAddress != null;
+
+ Set<User> reviewers = new HashSet<>();
+ Set<User> assignees = new HashSet<>();
+ if (event instanceof PullRequestOpened) {
+ for (PullRequestReview review : request.getReviews()) {
+ if (review.getStatus() == Status.PENDING)
+ reviewers.add(review.getUser());
+ }
+ for (PullRequestAssignment assignment : request.getAssignments())
+ assignees.add(assignment.getUser());
+ } else if (event instanceof PullRequestChanged) {
+ PullRequestChanged changeEvent = (PullRequestChanged) event;
+ PullRequestChangeData changeData = changeEvent.getChange().getData();
+ if ((changeData instanceof PullRequestApproveData
+ || changeData instanceof PullRequestRequestedForChangesData
+ || changeData instanceof PullRequestDiscardData)
+ && request.getSubmitter() != null && !notifiedUsers.contains(request.getSubmitter())) {
+ String subject = String.format(
+ "[Pull Request %s] (%s) %s",
+ request.getReference(),
+ WordUtils.capitalize(changeData.getActivity()),
+ emojis.apply(request.getTitle()));
+ String threadingReferences = String.format("<%s-%s@onedev>",
+ changeData.getActivity().replace(' ', '-'), request.getUUID());
+ EmailAddress emailAddress = request.getSubmitter().getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified()) {
+ mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
+ Lists.newArrayList(), Lists.newArrayList(), subject,
+ getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, null),
+ getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
+ replyAddress, senderName, threadingReferences);
+ }
+ notifiedUsers.add(request.getSubmitter());
}
- notifiedUsers.add(request.getSubmitter());
+ } else if (event instanceof PullRequestAssigned) {
+ assignees.add(((PullRequestAssigned) event).getAssignee());
+ } else if (event instanceof PullRequestReviewRequested) {
+ reviewers.add(((PullRequestReviewRequested) event).getReviewer());
}
- } else if (event instanceof PullRequestAssigned) {
- assignees.add(((PullRequestAssigned) event).getAssignee());
- } else if (event instanceof PullRequestReviewRequested) {
- reviewers.add(((PullRequestReviewRequested) event).getReviewer());
- }
-
- for (User assignee : assignees) {
- watchManager.watch(request, assignee, true);
- if (!notifiedUsers.contains(assignee)) {
- String subject = String.format(
- "[Pull Request %s] (Assigned) %s",
- request.getReference(),
- emojis.apply(request.getTitle()));
- String threadingReferences = String.format("<assigned-%s@onedev>", request.getUUID());
- String assignmentSummary;
- if (user != null)
- assignmentSummary = user.getDisplayName() + " assigned to you";
- else
- assignmentSummary = "Assigned to you";
- EmailAddress emailAddress = assignee.getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified()) {
- mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
- Lists.newArrayList(), Lists.newArrayList(), subject,
- getEmailBody(true, event, assignmentSummary, event.getHtmlBody(), url, replyable, null),
- getEmailBody(false, event, assignmentSummary, event.getTextBody(), url, replyable, null),
- replyAddress, senderName, threadingReferences);
+
+ for (User assignee : assignees) {
+ if (!assignee.isServiceAccount())
+ watchManager.watch(request, assignee, true);
+ if (!notifiedUsers.contains(assignee)) {
+ String subject = String.format(
+ "[Pull Request %s] (Assigned) %s",
+ request.getReference(),
+ emojis.apply(request.getTitle()));
+ String threadingReferences = String.format("<assigned-%s@onedev>", request.getUUID());
+ String assignmentSummary;
+ if (user != null)
+ assignmentSummary = user.getDisplayName() + " assigned to you";
+ else
+ assignmentSummary = "Assigned to you";
+ EmailAddress emailAddress = assignee.getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified()) {
+ mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
+ Lists.newArrayList(), Lists.newArrayList(), subject,
+ getEmailBody(true, event, assignmentSummary, event.getHtmlBody(), url, replyable, null),
+ getEmailBody(false, event, assignmentSummary, event.getTextBody(), url, replyable, null),
+ replyAddress, senderName, threadingReferences);
+ }
+ notifiedUsers.add(assignee);
}
- notifiedUsers.add(assignee);
}
- }
-
- for (User reviewer : reviewers) {
- watchManager.watch(request, reviewer, true);
- if (!notifiedUsers.contains(reviewer)) {
- String subject = String.format(
- "[Pull Request %s] (Review Request) %s",
- request.getReference(),
- emojis.apply(request.getTitle()));
- String threadingReferences = String.format("<review-invitation-%s@onedev>", request.getUUID());
- String reviewInvitationSummary;
- if (user != null)
- reviewInvitationSummary = user.getDisplayName() + " requested review from you";
- else
- reviewInvitationSummary = "Requested review from you";
-
- EmailAddress emailAddress = reviewer.getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified()) {
- mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
- Lists.newArrayList(), Lists.newArrayList(), subject,
- getEmailBody(true, event, reviewInvitationSummary, event.getHtmlBody(), url, replyable, null),
- getEmailBody(false, event, reviewInvitationSummary, event.getTextBody(), url, replyable, null),
- replyAddress, senderName, threadingReferences);
+
+ for (User reviewer : reviewers) {
+ if (!reviewer.isServiceAccount())
+ watchManager.watch(request, reviewer, true);
+ if (!notifiedUsers.contains(reviewer)) {
+ String subject = String.format(
+ "[Pull Request %s] (Review Request) %s",
+ request.getReference(),
+ emojis.apply(request.getTitle()));
+ String threadingReferences = String.format("<review-invitation-%s@onedev>", request.getUUID());
+ String reviewInvitationSummary;
+ if (user != null)
+ reviewInvitationSummary = user.getDisplayName() + " requested review from you";
+ else
+ reviewInvitationSummary = "Requested review from you";
+
+ EmailAddress emailAddress = reviewer.getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified()) {
+ mailManager.sendMailAsync(Lists.newArrayList(emailAddress.getValue()),
+ Lists.newArrayList(), Lists.newArrayList(), subject,
+ getEmailBody(true, event, reviewInvitationSummary, event.getHtmlBody(), url, replyable, null),
+ getEmailBody(false, event, reviewInvitationSummary, event.getTextBody(), url, replyable, null),
+ replyAddress, senderName, threadingReferences);
+ }
+ notifiedUsers.add(reviewer);
}
- notifiedUsers.add(reviewer);
}
- }
-
- if (event.getCommentText() instanceof MarkdownText) {
- MarkdownText markdown = (MarkdownText) event.getCommentText();
- for (String userName : new MentionParser().parseMentions(markdown.getRendered())) {
- User mentionedUser = userManager.findByName(userName);
- if (mentionedUser != null) {
- mentionManager.mention(request, mentionedUser);
- watchManager.watch(request, mentionedUser, true);
- if (!isNotified(notifiedEmailAddresses, mentionedUser)) {
- String subject = String.format(
- "[Pull Request %s] (Mentioned You) %s",
- request.getReference(),
- emojis.apply(request.getTitle()));
- String threadingReferences = String.format("<mentioned-%s@onedev>", request.getUUID());
-
- EmailAddress emailAddress = mentionedUser.getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified()) {
- mailManager.sendMailAsync(Sets.newHashSet(emailAddress.getValue()),
- Sets.newHashSet(), Sets.newHashSet(), subject,
- getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, null),
- getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
- replyAddress, senderName, threadingReferences);
+
+ if (event.getCommentText() instanceof MarkdownText) {
+ MarkdownText markdown = (MarkdownText) event.getCommentText();
+ for (String userName : new MentionParser().parseMentions(markdown.getRendered())) {
+ User mentionedUser = userManager.findByName(userName);
+ if (mentionedUser != null) {
+ mentionManager.mention(request, mentionedUser);
+ if (!mentionedUser.isServiceAccount())
+ watchManager.watch(request, mentionedUser, true);
+ if (!isNotified(notifiedEmailAddresses, mentionedUser)) {
+ String subject = String.format(
+ "[Pull Request %s] (Mentioned You) %s",
+ request.getReference(),
+ emojis.apply(request.getTitle()));
+ String threadingReferences = String.format("<mentioned-%s@onedev>", request.getUUID());
+
+ EmailAddress emailAddress = mentionedUser.getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified()) {
+ mailManager.sendMailAsync(Sets.newHashSet(emailAddress.getValue()),
+ Sets.newHashSet(), Sets.newHashSet(), subject,
+ getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, null),
+ getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
+ replyAddress, senderName, threadingReferences);
+ }
+ notifiedUsers.add(mentionedUser);
}
- notifiedUsers.add(mentionedUser);
}
}
}
- }
-
- if (!event.isMinor()) {
- Collection<String> bccEmailAddresses = new HashSet<>();
- if (user != null && !notifiedUsers.contains(user)
- && user.getPrimaryEmailAddress() != null
- && user.getPrimaryEmailAddress().isVerified()) {
- bccEmailAddresses.add(user.getPrimaryEmailAddress().getValue());
- }
-
- for (PullRequestWatch watch : request.getWatches()) {
- Date visitDate = userInfoManager.getPullRequestVisitDate(watch.getUser(), request);
- Permission permission = new ProjectPermission(request.getProject(), new ReadCode());
- if (watch.isWatching()
- && (visitDate == null || visitDate.before(event.getDate()))
- && (!(event instanceof PullRequestUpdated) || !watch.getUser().equals(request.getSubmitter()))
- && !notifiedUsers.contains(watch.getUser())
- && !isNotified(notifiedEmailAddresses, watch.getUser())
- && watch.getUser().asSubject().isPermitted(permission)) {
- EmailAddress emailAddress = watch.getUser().getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified())
- bccEmailAddresses.add(emailAddress.getValue());
+
+ if (!event.isMinor()) {
+ Collection<String> bccEmailAddresses = new HashSet<>();
+ if (user != null && !notifiedUsers.contains(user)
+ && user.getPrimaryEmailAddress() != null
+ && user.getPrimaryEmailAddress().isVerified()) {
+ bccEmailAddresses.add(user.getPrimaryEmailAddress().getValue());
}
- }
-
- if (!bccEmailAddresses.isEmpty()) {
- String subject = String.format(
- "[Pull Request %s] (%s) %s",
- request.getReference(),
- (event instanceof PullRequestOpened) ? "Opened" : "Updated",
- emojis.apply(request.getTitle()));
- String threadingReferences = "<" + request.getUUID() + "@onedev>";
- Unsubscribable unsubscribable = new Unsubscribable(mailManager.getUnsubscribeAddress(request));
- String htmlBody = getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, unsubscribable);
- String textBody = getEmailBody(false, event, summary, event.getTextBody(), url, replyable, unsubscribable);
- mailManager.sendMailAsync(
- Lists.newArrayList(), Lists.newArrayList(),
- bccEmailAddresses, subject, htmlBody, textBody,
- replyAddress, senderName, threadingReferences);
- }
+
+ for (PullRequestWatch watch : request.getWatches()) {
+ Date visitDate = userInfoManager.getPullRequestVisitDate(watch.getUser(), request);
+ Permission permission = new ProjectPermission(request.getProject(), new ReadCode());
+ if (watch.isWatching()
+ && (visitDate == null || visitDate.before(event.getDate()))
+ && (!(event instanceof PullRequestUpdated) || !watch.getUser().equals(request.getSubmitter()))
+ && !notifiedUsers.contains(watch.getUser())
+ && !isNotified(notifiedEmailAddresses, watch.getUser())
+ && watch.getUser().asSubject().isPermitted(permission)) {
+ EmailAddress emailAddress = watch.getUser().getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified())
+ bccEmailAddresses.add(emailAddress.getValue());
+ }
+ }
+
+ if (!bccEmailAddresses.isEmpty()) {
+ String subject = String.format(
+ "[Pull Request %s] (%s) %s",
+ request.getReference(),
+ (event instanceof PullRequestOpened) ? "Opened" : "Updated",
+ emojis.apply(request.getTitle()));
+ String threadingReferences = "<" + request.getUUID() + "@onedev>";
+ Unsubscribable unsubscribable = new Unsubscribable(mailManager.getUnsubscribeAddress(request));
+ String htmlBody = getEmailBody(true, event, summary, event.getHtmlBody(), url, replyable, unsubscribable);
+ String textBody = getEmailBody(false, event, summary, event.getTextBody(), url, replyable, unsubscribable);
+ mailManager.sendMailAsync(
+ Lists.newArrayList(), Lists.newArrayList(),
+ bccEmailAddresses, subject, htmlBody, textBody,
+ replyAddress, senderName, threadingReferences);
+ }
+ }
}
}
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/EmailAddressResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/EmailAddressResource.java
index 8557d5bebe..2a3affc4c5 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/EmailAddressResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/EmailAddressResource.java
@@ -61,7 +61,8 @@ public class EmailAddressResource {
var owner = emailAddress.getOwner();
if (!SecurityUtils.isAdministrator() && !owner.equals(getAuthUser()))
throw new UnauthorizedException();
-
+ if (owner.isServiceAccount())
+ throw new ExplicitException("Can not set email address for service account");
if (emailAddressManager.findByValue(emailAddress.getValue()) != null)
throw new ExplicitException("This email address is already used by another user");
diff --git a/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java b/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
index 80185c1a90..d99c63d103 100644
--- a/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
+++ b/server-core/src/main/java/io/onedev/server/rest/resource/UserResource.java
@@ -1,11 +1,58 @@
package io.onedev.server.rest.resource;
+import static java.util.stream.Collectors.toList;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import javax.validation.Valid;
+import javax.validation.constraints.Email;
+import javax.validation.constraints.NotEmpty;
+import javax.validation.constraints.NotNull;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.NotFoundException;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+import org.apache.shiro.authc.credential.PasswordService;
+import org.apache.shiro.authz.UnauthenticatedException;
+import org.apache.shiro.authz.UnauthorizedException;
+
import io.onedev.commons.utils.ExplicitException;
import io.onedev.server.annotation.UserName;
import io.onedev.server.entitymanager.EmailAddressManager;
import io.onedev.server.entitymanager.SshKeyManager;
import io.onedev.server.entitymanager.UserManager;
-import io.onedev.server.model.*;
+import io.onedev.server.model.AccessToken;
+import io.onedev.server.model.BuildQueryPersonalization;
+import io.onedev.server.model.CodeCommentQueryPersonalization;
+import io.onedev.server.model.CommitQueryPersonalization;
+import io.onedev.server.model.EmailAddress;
+import io.onedev.server.model.IssueQueryPersonalization;
+import io.onedev.server.model.IssueVote;
+import io.onedev.server.model.IssueWatch;
+import io.onedev.server.model.Membership;
+import io.onedev.server.model.PullRequestAssignment;
+import io.onedev.server.model.PullRequestQueryPersonalization;
+import io.onedev.server.model.PullRequestReview;
+import io.onedev.server.model.PullRequestWatch;
+import io.onedev.server.model.SshKey;
+import io.onedev.server.model.User;
+import io.onedev.server.model.UserAuthorization;
import io.onedev.server.model.support.NamedProjectQuery;
import io.onedev.server.model.support.build.NamedBuildQuery;
import io.onedev.server.model.support.issue.NamedIssueQuery;
@@ -13,21 +60,6 @@ import io.onedev.server.model.support.pullrequest.NamedPullRequestQuery;
import io.onedev.server.rest.annotation.Api;
import io.onedev.server.rest.annotation.EntityCreate;
import io.onedev.server.security.SecurityUtils;
-import org.apache.shiro.authc.credential.PasswordService;
-import org.apache.shiro.authz.UnauthenticatedException;
-import org.apache.shiro.authz.UnauthorizedException;
-
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import javax.validation.Valid;
-import javax.validation.constraints.Email;
-import javax.validation.constraints.NotEmpty;
-import javax.validation.constraints.NotNull;
-import javax.ws.rs.*;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import java.io.Serializable;
-import java.util.*;
@Api(order=5000)
@Path("/users")
@@ -53,24 +85,34 @@ public class UserResource {
this.emailAddressManager = emailAddressManager;
}
+ private ProfileData getProfileData(User user) {
+ var profile = new ProfileData();
+ profile.setServiceAccount(user.isServiceAccount());
+ profile.setName(user.getName());
+ profile.setFullName(user.getFullName());
+ if (!user.isServiceAccount())
+ profile.setNotifyOwnEvents(user.isNotifyOwnEvents());
+ return profile;
+ }
+
@Api(order=100)
@Path("/{userId}")
@GET
- public User getProfile(@PathParam("userId") Long userId) {
+ public ProfileData getProfile(@PathParam("userId") Long userId) {
User user = userManager.load(userId);
if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getAuthUser()))
throw new UnauthorizedException();
- return user;
+ return getProfileData(user);
}
@Api(order=200)
@Path("/me")
@GET
- public User getMyProfile() {
+ public ProfileData getMyProfile() {
User user = SecurityUtils.getAuthUser();
if (user == null)
throw new UnauthorizedException();
- return user;
+ return getProfileData(user);
}
@Api(order=250)
@@ -241,14 +283,14 @@ public class UserResource {
@Api(order=1800)
@GET
- public List<User> queryProfile(
+ public List<ProfileData> queryProfile(
@QueryParam("term") @Api(description="Any string in login name, full name or email address") String term,
@QueryParam("offset") @Api(example="0") int offset,
@QueryParam("count") @Api(example="100") int count) {
if (!SecurityUtils.isAdministrator())
throw new UnauthorizedException();
- return userManager.query(term, offset, count);
+ return userManager.query(term, offset, count).stream().map(this::getProfileData).collect(toList());
}
@Api(order=1850)
@@ -268,23 +310,27 @@ public class UserResource {
if (SecurityUtils.isAdministrator()) {
if (userManager.findByName(data.getName()) != null)
throw new ExplicitException("Login name is already used by another user");
- if (emailAddressManager.findByValue(data.getEmailAddress()) != null)
+ if (!data.isServiceAccount() && emailAddressManager.findByValue(data.getEmailAddress()) != null)
throw new ExplicitException("Email address is already used by another user");
User user = new User();
+ user.setServiceAccount(data.isServiceAccount());
user.setName(data.getName());
user.setFullName(data.getFullName());
- user.setPassword(passwordService.encryptPassword(data.getPassword()));
- userManager.create(user);
-
- EmailAddress emailAddress = new EmailAddress();
- emailAddress.setGit(true);
- emailAddress.setPrimary(true);
- emailAddress.setOwner(user);
- emailAddress.setValue(data.getEmailAddress());
- emailAddress.setVerificationCode(null);
- emailAddressManager.create(emailAddress);
-
+ if (data.isServiceAccount()) {
+ userManager.create(user);
+ } else {
+ user.setNotifyOwnEvents(data.isNotifyOwnEvents());
+ user.setPassword(passwordService.encryptPassword(data.getPassword()));
+ userManager.create(user);
+ EmailAddress emailAddress = new EmailAddress();
+ emailAddress.setGit(true);
+ emailAddress.setPrimary(true);
+ emailAddress.setOwner(user);
+ emailAddress.setValue(data.getEmailAddress());
+ emailAddress.setVerificationCode(null);
+ emailAddressManager.create(emailAddress);
+ }
return user.getId();
} else {
throw new UnauthenticatedException();
@@ -304,6 +350,8 @@ public class UserResource {
String oldName = user.getName();
user.setName(data.getName());
user.setFullName(data.getFullName());
+ if (!user.isServiceAccount())
+ user.setNotifyOwnEvents(data.isNotifyOwnEvents());
userManager.update(user, oldName);
return Response.ok().build();
} else {
@@ -320,6 +368,8 @@ public class UserResource {
user.setPassword(passwordService.encryptPassword(password));
userManager.update(user, null);
return Response.ok().build();
+ } else if (user.isServiceAccount()) {
+ throw new ExplicitException("Can not set password for service account");
} else if (user.equals(SecurityUtils.getAuthUser())) {
if (user.getPassword() == null) {
throw new ExplicitException("The user is currently authenticated via external system, "
@@ -339,6 +389,8 @@ public class UserResource {
@DELETE
public Response resetTwoFactorAuthentication(@PathParam("userId") Long userId) {
User user = userManager.load(userId);
+ if (user.isServiceAccount())
+ throw new ExplicitException("Can not reset two factor authentication for service account");
if (SecurityUtils.isAdministrator()) {
user.setTwoFactorAuthentication(null);
userManager.update(user, null);
@@ -355,6 +407,8 @@ public class UserResource {
User user = userManager.load(userId);
if (!SecurityUtils.isAdministrator() && !user.equals(SecurityUtils.getAuthUser()))
throw new UnauthorizedException();
+ if (user.isServiceAccount())
+ throw new ExplicitException("Can not set queries and watches for service account");
user.setBuildQuerySubscriptions(queriesAndWatches.buildQuerySubscriptions);
user.setIssueQueryWatches(queriesAndWatches.issueQueryWatches);
user.setPullRequestQueryWatches(queriesAndWatches.pullRequestQueryWatches);
@@ -406,15 +460,36 @@ public class UserResource {
private static final long serialVersionUID = 1L;
+ @Api(order=50, exampleProvider="getServiceAccountExample", description="Create user as service account")
+ private boolean serviceAccount;
+
+ @Api(order=100, description="Login name of the user")
private String name;
+ @Api(order=150, description = "Password of the user. Only required if not created as service account")
private String password;
private String fullName;
+ @Api(order=300, description = "Email address of the user. Only required if not created as service account")
private String emailAddress;
- @Api(order=100, description="Login name of the user")
+ @Api(order=400, description = "Whether or not to notify user on own events. Only required if not created as service account")
+ private boolean notifyOwnEvents;
+
+ public boolean isServiceAccount() {
+ return serviceAccount;
+ }
+
+ public void setServiceAccount(boolean serviceAccount) {
+ this.serviceAccount = serviceAccount;
+ }
+
+ @SuppressWarnings("unused")
+ private static boolean getServiceAccountExample() {
+ return false;
+ }
+
@UserName
@NotEmpty
public String getName() {
@@ -425,7 +500,6 @@ public class UserResource {
this.name = name;
}
- @Api(order=150)
@NotEmpty
public String getPassword() {
return password;
@@ -444,7 +518,6 @@ public class UserResource {
this.fullName = fullName;
}
- @Api(order=300)
@Email
@NotEmpty
public String getEmailAddress() {
@@ -455,17 +528,76 @@ public class UserResource {
this.emailAddress = emailAddress;
}
+ public boolean isNotifyOwnEvents() {
+ return notifyOwnEvents;
+ }
+
+ public void setNotifyOwnEvents(boolean notifyOwnEvents) {
+ this.notifyOwnEvents = notifyOwnEvents;
+ }
}
-
- public static class ProfileUpdateData implements Serializable {
+ public static class ProfileData implements Serializable {
private static final long serialVersionUID = 1L;
+ @Api(order=50, description="Whether or not the user is a service account")
+ private boolean serviceAccount;
+
+ @Api(order=100, description="Login name of the user")
private String name;
+ @Api(order=200)
private String fullName;
+
+ @Api(order=300, description = "Whether or not to notify user on own events. Only meaningful for non service account")
+ private boolean notifyOwnEvents;
+
+ public boolean isServiceAccount() {
+ return serviceAccount;
+ }
+
+ public void setServiceAccount(boolean serviceAccount) {
+ this.serviceAccount = serviceAccount;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getFullName() {
+ return fullName;
+ }
+
+ public void setFullName(String fullName) {
+ this.fullName = fullName;
+ }
+
+ public boolean isNotifyOwnEvents() {
+ return notifyOwnEvents;
+ }
+
+ public void setNotifyOwnEvents(boolean notifyOwnEvents) {
+ this.notifyOwnEvents = notifyOwnEvents;
+ }
+ }
+
+ public static class ProfileUpdateData implements Serializable {
+
+ private static final long serialVersionUID = 1L;
@Api(order=100, description="Login name of the user")
+ private String name;
+
+ @Api(order=200)
+ private String fullName;
+
+ @Api(order=300, description = "Whether or not to notify user on own events. Only required for non service account")
+ private boolean notifyOwnEvents;
+
@UserName
@NotEmpty
public String getName() {
@@ -476,7 +608,6 @@ public class UserResource {
this.name = name;
}
- @Api(order=200)
public String getFullName() {
return fullName;
}
@@ -485,6 +616,13 @@ public class UserResource {
this.fullName = fullName;
}
+ public boolean isNotifyOwnEvents() {
+ return notifyOwnEvents;
+ }
+
+ public void setNotifyOwnEvents(boolean notifyOwnEvents) {
+ this.notifyOwnEvents = notifyOwnEvents;
+ }
}
public static class QueriesAndWatches implements Serializable {
diff --git a/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthenticatingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthenticatingRealm.java
index d81fe83128..22299f303a 100644
--- a/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthenticatingRealm.java
+++ b/server-core/src/main/java/io/onedev/server/security/realm/PasswordAuthenticatingRealm.java
@@ -137,6 +137,8 @@ public class PasswordAuthenticatingRealm extends AuthenticatingRealm {
else
user = userManager.findByName(userNameOrEmailAddressValue);
if (user != null) {
+ if (user.isServiceAccount())
+ throw new AuthenticationException("Login not supported for service account");
if (user.getPassword() == null) {
Authenticator authenticator = settingManager.getAuthenticator();
if (authenticator != null) {
diff --git a/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthenticatingRealm.java b/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthenticatingRealm.java
index 72c40ba19a..eba8dce088 100644
--- a/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthenticatingRealm.java
+++ b/server-core/src/main/java/io/onedev/server/security/realm/SsoAuthenticatingRealm.java
@@ -1,22 +1,32 @@
package io.onedev.server.security.realm;
-import com.google.common.collect.Sets;
-import io.onedev.server.entitymanager.*;
-import io.onedev.server.model.EmailAddress;
-import io.onedev.server.model.User;
-import io.onedev.server.model.support.administration.sso.SsoAuthenticated;
-import io.onedev.server.persistence.SessionManager;
-import io.onedev.server.persistence.TransactionManager;
+import java.util.Collection;
+import java.util.concurrent.Callable;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.realm.AuthenticatingRealm;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import java.util.Collection;
-import java.util.concurrent.Callable;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Sets;
+
+import io.onedev.server.entitymanager.EmailAddressManager;
+import io.onedev.server.entitymanager.GroupManager;
+import io.onedev.server.entitymanager.MembershipManager;
+import io.onedev.server.entitymanager.ProjectManager;
+import io.onedev.server.entitymanager.SettingManager;
+import io.onedev.server.entitymanager.SshKeyManager;
+import io.onedev.server.entitymanager.UserManager;
+import io.onedev.server.model.EmailAddress;
+import io.onedev.server.model.User;
+import io.onedev.server.model.support.administration.sso.SsoAuthenticated;
+import io.onedev.server.persistence.SessionManager;
+import io.onedev.server.persistence.TransactionManager;
@Singleton
public class SsoAuthenticatingRealm extends AuthenticatingRealm {
@@ -112,6 +122,7 @@ public class SsoAuthenticatingRealm extends AuthenticatingRealm {
&& userManager.findByName(userName) != null) {
throw new AuthenticationException("Login name '" + userName + "' already used by another user");
} else {
+ Preconditions.checkState(!emailAddress.getOwner().isServiceAccount());
updateUser(emailAddress, authenticated);
return emailAddress.getOwner();
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/commit/list/commit-list.css b/server-core/src/main/java/io/onedev/server/web/component/commit/list/commit-list.css
index ed22b39cd4..fe5875b153 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/commit/list/commit-list.css
+++ b/server-core/src/main/java/io/onedev/server/web/component/commit/list/commit-list.css
@@ -174,6 +174,6 @@
.commit-filter-edit {
min-width: 360px;
- max-width: 400px;
+ max-width: 420px;
padding: 1rem;
}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java b/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
index 64bd0cf014..c28bf2db5a 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
@@ -107,7 +107,7 @@ public abstract class EntityWatchesPanel extends Panel {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(SecurityUtils.getAuthUser() != null);
+ setVisible(SecurityUtils.getAuthUser() != null && !SecurityUtils.getAuthUser().isServiceAccount());
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/component/filteredit/filter-edit.css b/server-core/src/main/java/io/onedev/server/web/component/filteredit/filter-edit.css
index 09d948aec7..34ac497924 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/filteredit/filter-edit.css
+++ b/server-core/src/main/java/io/onedev/server/web/component/filteredit/filter-edit.css
@@ -1,5 +1,5 @@
.filter-edit {
min-width: 360px;
- max-width: 400px;
+ max-width: 420px;
padding: 1rem;
}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.html b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.html
index 7953e69109..8376fd86af 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.html
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.html
@@ -29,6 +29,7 @@
<div wicket:id="builtInFieldsEditor"></div>
<div wicket:id="customFieldsEditor"></div>
<div wicket:id="comment" class="mb-4" placeholder="Leave a comment"></div>
+ <wicket:enclosure>
<div class="form-group">
<label class="name control-label">
<span>Send Notifications</span>
@@ -42,6 +43,7 @@
</div>
<div class="text-muted form-text">Whether or not to send notifications to issue watchers for this change</div>
</div>
+ </wicket:enclosure>
</div>
<div class="modal-footer">
<input wicket:id="save" type="submit" class="btn btn-primary" value="Save">
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
index a62beb9329..4fd64d8e00 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/list/BatchEditPanel.java
@@ -263,7 +263,8 @@ abstract class BatchEditPanel extends Panel implements InputContext {
});
- form.add(new CheckBox("sendNotifications", new PropertyModel<>(this, "sendNotifications")));
+ form.add(new CheckBox("sendNotifications", new PropertyModel<>(this, "sendNotifications"))
+ .setVisible(!SecurityUtils.getUser().isServiceAccount()));
form.add(new AjaxButton("save") {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
index dc34b3ab34..f7f92a2014 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/issue/list/IssueListPanel.java
@@ -975,61 +975,63 @@ public abstract class IssueListPanel extends Panel {
});
}
- menuItems.add(new MenuItem() {
+ if (!SecurityUtils.getAuthUser().isServiceAccount()) {
+ menuItems.add(new MenuItem() {
- @Override
- public String getLabel() {
- return "Watch/Unwatch Selected Issues";
- }
+ @Override
+ public String getLabel() {
+ return "Watch/Unwatch Selected Issues";
+ }
- @Override
- public WebMarkupContainer newLink(String id) {
- return new DropdownLink(id) {
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
- @Override
- protected Component newContent(String id, FloatingPanel dropdown2) {
- return new WatchStatusPanel(id) {
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new WatchStatusPanel(id) {
- @Override
- protected WatchStatus getWatchStatus() {
- return null;
- }
+ @Override
+ protected WatchStatus getWatchStatus() {
+ return null;
+ }
- @Override
- protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
- dropdown.close();
- dropdown2.close();
+ @Override
+ protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
+ dropdown.close();
+ dropdown2.close();
- var issues = selectionColumn.getSelections().stream()
- .map(it->it.getObject()).collect(toList());
- getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), issues, watchStatus);
- selectionColumn.getSelections().clear();
- Session.get().success("Watch status changed");
- }
- };
- }
+ var issues = selectionColumn.getSelections().stream()
+ .map(it->it.getObject()).collect(toList());
+ getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), issues, watchStatus);
+ selectionColumn.getSelections().clear();
+ Session.get().success("Watch status changed");
+ }
+ };
+ }
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(!selectionColumn.getSelections().isEmpty());
- }
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(!selectionColumn.getSelections().isEmpty());
+ }
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- tag.put("title", "Please select issues to watch/unwatch");
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "Please select issues to watch/unwatch");
+ }
}
- }
- };
- }
+ };
+ }
+
+ });
+ }
- });
-
if (getProject() != null && getProject().isTimeTracking()
&& SecurityUtils.canManageIssues(getProject())
&& WicketUtils.isSubscriptionActive()) {
@@ -1390,60 +1392,62 @@ public abstract class IssueListPanel extends Panel {
});
}
- menuItems.add(new MenuItem() {
+ if (!SecurityUtils.getAuthUser().isServiceAccount()) {
+ menuItems.add(new MenuItem() {
- @Override
- public String getLabel() {
- return "Watch/Unwatch All Queried Issues";
- }
+ @Override
+ public String getLabel() {
+ return "Watch/Unwatch All Queried Issues";
+ }
- @Override
- public WebMarkupContainer newLink(String id) {
- return new DropdownLink(id) {
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
- @Override
- protected Component newContent(String id, FloatingPanel dropdown2) {
- return new WatchStatusPanel(id) {
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new WatchStatusPanel(id) {
- @Override
- protected WatchStatus getWatchStatus() {
- return null;
- }
+ @Override
+ protected WatchStatus getWatchStatus() {
+ return null;
+ }
- @Override
- protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
- dropdown.close();
- dropdown2.close();
+ @Override
+ protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
+ dropdown.close();
+ dropdown2.close();
- Collection<Issue> issues = new ArrayList<>();
- for (@SuppressWarnings("unchecked") var it = (Iterator<Issue>) dataProvider.iterator(0, issuesTable.getItemCount()); it.hasNext(); )
- issues.add(it.next());
- getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), issues, watchStatus);
- Session.get().success("Watch status changed");
- }
+ Collection<Issue> issues = new ArrayList<>();
+ for (@SuppressWarnings("unchecked") var it = (Iterator<Issue>) dataProvider.iterator(0, issuesTable.getItemCount()); it.hasNext(); )
+ issues.add(it.next());
+ getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), issues, watchStatus);
+ Session.get().success("Watch status changed");
+ }
- };
- }
+ };
+ }
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(issuesTable.getItemCount() != 0);
- }
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(issuesTable.getItemCount() != 0);
+ }
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- tag.put("title", "No issues to watch/unwatch");
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "No issues to watch/unwatch");
+ }
}
- }
- };
- }
+ };
+ }
- });
+ });
+ }
menuItems.add(new MenuItem() {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/pullrequest/list/PullRequestListPanel.java b/server-core/src/main/java/io/onedev/server/web/component/pullrequest/list/PullRequestListPanel.java
index 41d5f60277..44201cd15e 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/pullrequest/list/PullRequestListPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/pullrequest/list/PullRequestListPanel.java
@@ -261,61 +261,63 @@ public abstract class PullRequestListPanel extends Panel {
protected List<MenuItem> getMenuItems(FloatingPanel dropdown) {
List<MenuItem> menuItems = new ArrayList<>();
- menuItems.add(new MenuItem() {
+ if (!SecurityUtils.getAuthUser().isServiceAccount()) {
+ menuItems.add(new MenuItem() {
- @Override
- public String getLabel() {
- return "Watch/Unwatch Selected Pull Requests";
- }
+ @Override
+ public String getLabel() {
+ return "Watch/Unwatch Selected Pull Requests";
+ }
- @Override
- public WebMarkupContainer newLink(String id) {
- return new DropdownLink(id) {
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
- @Override
- protected Component newContent(String id, FloatingPanel dropdown2) {
- return new WatchStatusPanel(id) {
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new WatchStatusPanel(id) {
- @Override
- protected WatchStatus getWatchStatus() {
- return null;
- }
+ @Override
+ protected WatchStatus getWatchStatus() {
+ return null;
+ }
- @Override
- protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
- dropdown.close();
- dropdown2.close();
+ @Override
+ protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
+ dropdown.close();
+ dropdown2.close();
- var requests = selectionColumn.getSelections().stream()
- .map(it->it.getObject()).collect(toList());
- getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), requests, watchStatus);
- selectionColumn.getSelections().clear();
- Session.get().success("Watch status changed");
- }
- };
- }
+ var requests = selectionColumn.getSelections().stream()
+ .map(it->it.getObject()).collect(toList());
+ getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), requests, watchStatus);
+ selectionColumn.getSelections().clear();
+ Session.get().success("Watch status changed");
+ }
+ };
+ }
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(!selectionColumn.getSelections().isEmpty());
- }
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(!selectionColumn.getSelections().isEmpty());
+ }
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- tag.put("title", "Please select pull requests to watch/unwatch");
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "Please select pull requests to watch/unwatch");
+ }
}
- }
- };
- }
+ };
+ }
+
+ });
+ }
- });
-
if (getProject() != null && SecurityUtils.canManagePullRequests(getProject())) {
menuItems.add(new MenuItem() {
@@ -455,60 +457,62 @@ public abstract class PullRequestListPanel extends Panel {
});
}
- menuItems.add(new MenuItem() {
+ if (!SecurityUtils.getAuthUser().isServiceAccount()) {
+ menuItems.add(new MenuItem() {
- @Override
- public String getLabel() {
- return "Watch/Unwatch All Queried Pull Requests";
- }
+ @Override
+ public String getLabel() {
+ return "Watch/Unwatch All Queried Pull Requests";
+ }
- @Override
- public WebMarkupContainer newLink(String id) {
- return new DropdownLink(id) {
+ @Override
+ public WebMarkupContainer newLink(String id) {
+ return new DropdownLink(id) {
- @Override
- protected Component newContent(String id, FloatingPanel dropdown2) {
- return new WatchStatusPanel(id) {
+ @Override
+ protected Component newContent(String id, FloatingPanel dropdown2) {
+ return new WatchStatusPanel(id) {
- @Override
- protected WatchStatus getWatchStatus() {
- return null;
- }
+ @Override
+ protected WatchStatus getWatchStatus() {
+ return null;
+ }
- @Override
- protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
- dropdown.close();
- dropdown2.close();
+ @Override
+ protected void onWatchStatusChange(AjaxRequestTarget target, WatchStatus watchStatus) {
+ dropdown.close();
+ dropdown2.close();
- Collection<PullRequest> requests = new ArrayList<>();
- for (@SuppressWarnings("unchecked") var it = (Iterator<PullRequest>) dataProvider.iterator(0, requestsTable.getItemCount()); it.hasNext(); )
- requests.add(it.next());
- getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), requests, watchStatus);
- Session.get().success("Watch status changed");
- }
+ Collection<PullRequest> requests = new ArrayList<>();
+ for (@SuppressWarnings("unchecked") var it = (Iterator<PullRequest>) dataProvider.iterator(0, requestsTable.getItemCount()); it.hasNext(); )
+ requests.add(it.next());
+ getWatchManager().setWatchStatus(SecurityUtils.getAuthUser(), requests, watchStatus);
+ Session.get().success("Watch status changed");
+ }
- };
- }
+ };
+ }
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setEnabled(requestsTable.getItemCount() != 0);
- }
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setEnabled(requestsTable.getItemCount() != 0);
+ }
- @Override
- protected void onComponentTag(ComponentTag tag) {
- super.onComponentTag(tag);
- configure();
- if (!isEnabled()) {
- tag.put("disabled", "disabled");
- tag.put("title", "No pull requests to watch/unwatch");
+ @Override
+ protected void onComponentTag(ComponentTag tag) {
+ super.onComponentTag(tag);
+ configure();
+ if (!isEnabled()) {
+ tag.put("disabled", "disabled");
+ tag.put("title", "No pull requests to watch/unwatch");
+ }
}
- }
- };
- }
+ };
+ }
- });
+ });
+ }
if (getProject() != null && SecurityUtils.canManagePullRequests(getProject())) {
menuItems.add(new MenuItem() {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/savedquery/SavedQueriesPanel.java b/server-core/src/main/java/io/onedev/server/web/component/savedquery/SavedQueriesPanel.java
index cb7db19cb5..19630aad74 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/savedquery/SavedQueriesPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/savedquery/SavedQueriesPanel.java
@@ -308,7 +308,7 @@ public abstract class SavedQueriesPanel<T extends NamedQuery> extends Panel {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(getQueryPersonalization().getQueryWatchSupport() != null);
+ setVisible(!SecurityUtils.getAuthUser().isServiceAccount() && getQueryPersonalization().getQueryWatchSupport() != null);
}
});
@@ -334,7 +334,7 @@ public abstract class SavedQueriesPanel<T extends NamedQuery> extends Panel {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(getQueryPersonalization().getQuerySubscriptionSupport() != null);
+ setVisible(!SecurityUtils.getAuthUser().isServiceAccount() && getQueryPersonalization().getQuerySubscriptionSupport() != null);
}
});
@@ -390,6 +390,7 @@ public abstract class SavedQueriesPanel<T extends NamedQuery> extends Panel {
protected void onConfigure() {
super.onConfigure();
setVisible(SecurityUtils.getAuthUser() != null
+ && !SecurityUtils.getAuthUser().isServiceAccount()
&& getQueryPersonalization() != null
&& getQueryPersonalization().getQueryWatchSupport() != null);
}
@@ -419,6 +420,7 @@ public abstract class SavedQueriesPanel<T extends NamedQuery> extends Panel {
protected void onConfigure() {
super.onConfigure();
setVisible(SecurityUtils.getAuthUser() != null
+ && !SecurityUtils.getAuthUser().isServiceAccount()
&& getQueryPersonalization() != null
&& getQueryPersonalization().getQuerySubscriptionSupport() != null);
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/user/profileedit/ProfileEditPanel.java b/server-core/src/main/java/io/onedev/server/web/component/user/profileedit/ProfileEditPanel.java
index 2bc4265271..89a4c2e348 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/user/profileedit/ProfileEditPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/user/profileedit/ProfileEditPanel.java
@@ -56,7 +56,7 @@ public class ProfileEditPanel extends GenericPanel<User> {
editor.getDescriptor().copyProperties(object, getUser());
}
- }, Sets.newHashSet("password"), true);
+ }, Sets.newHashSet("password", "serviceAccount"), true);
Form<?> form = new Form<Void>("form") {
diff --git a/server-core/src/main/java/io/onedev/server/web/component/watchstatus/WatchStatusLink.java b/server-core/src/main/java/io/onedev/server/web/component/watchstatus/WatchStatusLink.java
index 51b284cda3..e06f24ab00 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/watchstatus/WatchStatusLink.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/watchstatus/WatchStatusLink.java
@@ -31,7 +31,7 @@ public abstract class WatchStatusLink extends DropdownLink {
protected String load() {
WatchStatus status = getWatchStatus();
if (status == WatchStatus.IGNORE)
- return "do-not-watch";
+ return "ignore";
else if (status == WatchStatus.WATCH)
return "watch";
else
diff --git a/server-core/src/main/java/io/onedev/server/web/component/watchstatus/watch-status.css b/server-core/src/main/java/io/onedev/server/web/component/watchstatus/watch-status.css
index 90ef851768..3507b6a4e9 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/watchstatus/watch-status.css
+++ b/server-core/src/main/java/io/onedev/server/web/component/watchstatus/watch-status.css
@@ -7,7 +7,7 @@
.watch-status.watch:AFTER {
content: "Watch";
}
-.watch-status.do-not-watch:AFTER {
+.watch-status.ignore:AFTER {
content: "Ignore";
}
.watch-status .icon {
@@ -15,7 +15,7 @@
}
.watch-status.default .icon-bell,
.watch-status.watch .icon-bell-ring,
-.watch-status.do-not-watch .icon-bell-off {
+.watch-status.ignore .icon-bell-off {
display: inline-block;
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/NewUserPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/NewUserPage.java
index 0e7d8395b6..791e92260b 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/NewUserPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/NewUserPage.java
@@ -53,34 +53,38 @@ public class NewUserPage extends AdministrationPage {
User userWithSameName = getUserManager().findByName(bean.getName());
if (userWithSameName != null) {
editor.error(new Path(new PathNode.Named(User.PROP_NAME)),
- "Login name already used by another account");
+ "User name already used by another account");
}
- if (getEmailAddressManager().findByValue(bean.getEmailAddress()) != null) {
+ if (!bean.isServiceAccount() && getEmailAddressManager().findByValue(bean.getEmailAddress()) != null) {
editor.error(new Path(new PathNode.Named(NewUserBean.PROP_EMAIL_ADDRESS)),
"Email address already used by another user");
}
- if (editor.isValid()){
+ if (editor.isValid()) {
User user = new User();
user.setName(bean.getName());
user.setFullName(bean.getFullName());
- user.setPassword(AppLoader.getInstance(PasswordService.class).encryptPassword(bean.getPassword()));
-
- EmailAddress emailAddress = new EmailAddress();
- emailAddress.setValue(bean.getEmailAddress());
- emailAddress.setOwner(user);
- emailAddress.setVerificationCode(null);
-
- OneDev.getInstance(TransactionManager.class).run(new Runnable() {
-
- @Override
- public void run() {
- getUserManager().create(user);
- getEmailAddressManager().create(emailAddress);
- }
+ user.setServiceAccount(bean.isServiceAccount());
+ if (user.isServiceAccount()) {
+ getUserManager().create(user);
+ } else {
+ user.setPassword(AppLoader.getInstance(PasswordService.class).encryptPassword(bean.getPassword()));
+ EmailAddress emailAddress = new EmailAddress();
+ emailAddress.setValue(bean.getEmailAddress());
+ emailAddress.setOwner(user);
+ emailAddress.setVerificationCode(null);
- });
-
+ OneDev.getInstance(TransactionManager.class).run(new Runnable() {
+
+ @Override
+ public void run() {
+ getUserManager().create(user);
+ getEmailAddressManager().create(emailAddress);
+ }
+
+ });
+ }
+
Session.get().success("New user created");
if (continueToAdd) {
bean = new NewUserBean();
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.html
index 1d76cca62a..31f3455509 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.html
@@ -20,6 +20,7 @@
<a wicket:id="link">
<img wicket:id="avatar">
<span wicket:id="name" class="name"></span>
+ <span wicket:id="serviceAccount" class="badge badge-warning badge-sm ml-1">service</span>
</a>
</wicket:fragment>
<wicket:fragment wicket:id="actionsFrag">
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.java
index 9347fa760f..70506a4387 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserListPage.java
@@ -367,6 +367,7 @@ public class UserListPage extends AdministrationPage {
};
link.add(new UserAvatar("avatar", user));
link.add(new Label("name", user.getName()));
+ link.add(new Label("serviceAccount", "service").setVisible(user.isServiceAccount()));
fragment.add(link);
cellItem.add(fragment);
}
@@ -392,15 +393,19 @@ public class UserListPage extends AdministrationPage {
@Override
public void populateItem(Item<ICellPopulator<User>> cellItem, String componentId,
IModel<User> rowModel) {
- EmailAddress emailAddress = rowModel.getObject().getPrimaryEmailAddress();
- if (emailAddress != null) {
- Fragment fragment = new Fragment(componentId, "emailFrag", UserListPage.this);
- fragment.add(new Label("emailAddress", emailAddress.getValue()));
- fragment.add(new EmailAddressVerificationStatusBadge(
- "verificationStatus", Model.of(emailAddress)));
- cellItem.add(fragment);
+ if (rowModel.getObject().isServiceAccount()) {
+ cellItem.add(new Label(componentId, "<i>N/A</i>").setEscapeModelStrings(false));
} else {
- cellItem.add(new Label(componentId, "<i>Not specified</i>").setEscapeModelStrings(false));
+ EmailAddress emailAddress = rowModel.getObject().getPrimaryEmailAddress();
+ if (emailAddress != null) {
+ Fragment fragment = new Fragment(componentId, "emailFrag", UserListPage.this);
+ fragment.add(new Label("emailAddress", emailAddress.getValue()));
+ fragment.add(new EmailAddressVerificationStatusBadge(
+ "verificationStatus", Model.of(emailAddress)));
+ cellItem.add(fragment);
+ } else {
+ cellItem.add(new Label(componentId, "<i>Not specified</i>").setEscapeModelStrings(false));
+ }
}
}
@@ -415,7 +420,11 @@ public class UserListPage extends AdministrationPage {
@Override
public void populateItem(Item<ICellPopulator<User>> cellItem, String componentId, IModel<User> rowModel) {
- cellItem.add(new Label(componentId, rowModel.getObject().getAuthSource()));
+ if (rowModel.getObject().isServiceAccount()) {
+ cellItem.add(new Label(componentId, "<i>N/A</i>").setEscapeModelStrings(false));
+ } else {
+ cellItem.add(new Label(componentId, rowModel.getObject().getAuthSource()));
+ }
}
});
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserPage.java
index 43395a11d9..88aac59936 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/UserPage.java
@@ -72,19 +72,21 @@ public abstract class UserPage extends AdministrationPage implements UserAware {
var params = paramsOf(getUser());
tabs.add(new PageTab(Model.of("Profile"), Model.of("profile"), UserProfilePage.class, params));
- tabs.add(new PageTab(Model.of("Email Addresses"), Model.of("mail"), UserEmailAddressesPage.class, params));
+ if (!getUser().isServiceAccount())
+ tabs.add(new PageTab(Model.of("Email Addresses"), Model.of("mail"), UserEmailAddressesPage.class, params));
tabs.add(new PageTab(Model.of("Edit Avatar"), Model.of("avatar"), UserAvatarPage.class, params));
-
- tabs.add(new PageTab(Model.of("Password"), Model.of("password"), UserPasswordPage.class, params));
+ if (!getUser().isServiceAccount())
+ tabs.add(new PageTab(Model.of("Password"), Model.of("password"), UserPasswordPage.class, params));
tabs.add(new PageTab(Model.of("Belonging Groups"), Model.of("group"), UserMembershipsPage.class, params));
tabs.add(new PageTab(Model.of("Authorized Projects"), Model.of("project"), UserAuthorizationsPage.class, params));
if (OneDev.getInstance(ServerConfig.class).getSshPort() != 0)
tabs.add(new PageTab(Model.of("SSH Keys"), Model.of("key"), UserSshKeysPage.class, params));
tabs.add(new PageTab(Model.of("GPG Keys"), Model.of("key"), UserGpgKeysPage.class, params));
tabs.add(new PageTab(Model.of("Access Tokens"), Model.of("token"), UserAccessTokensPage.class, params));
- if (getUser().isEnforce2FA())
+ if (!getUser().isServiceAccount() && getUser().isEnforce2FA())
tabs.add(new PageTab(Model.of("Two-factor Authentication"), Model.of("shield"), UserTwoFactorAuthenticationPage.class, params));
- tabs.add(new PageTab(Model.of("Query Watches"), Model.of("bell"), UserQueryWatchesPage.class, params));
+ if (!getUser().isServiceAccount())
+ tabs.add(new PageTab(Model.of("Query Watches"), Model.of("bell"), UserQueryWatchesPage.class, params));
add(new Tabbable("userTabs", tabs));
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/emailaddresses/UserEmailAddressesPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/emailaddresses/UserEmailAddressesPage.java
index 8b34a22c78..8da0a10eda 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/emailaddresses/UserEmailAddressesPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/emailaddresses/UserEmailAddressesPage.java
@@ -11,6 +11,8 @@ public class UserEmailAddressesPage extends UserPage {
public UserEmailAddressesPage(PageParameters params) {
super(params);
+ if (getUser().isServiceAccount())
+ throw new IllegalStateException();
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/password/UserPasswordPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/password/UserPasswordPage.java
index 5a0827e0a5..325d2d2054 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/password/UserPasswordPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/password/UserPasswordPage.java
@@ -1,14 +1,17 @@
package io.onedev.server.web.page.admin.usermanagement.password;
-import io.onedev.server.web.component.user.passwordedit.PasswordEditPanel;
-import io.onedev.server.web.page.admin.usermanagement.UserPage;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.request.mapper.parameter.PageParameters;
+import io.onedev.server.web.component.user.passwordedit.PasswordEditPanel;
+import io.onedev.server.web.page.admin.usermanagement.UserPage;
+
public class UserPasswordPage extends UserPage {
public UserPasswordPage(PageParameters params) {
super(params);
+ if (getUser().isServiceAccount())
+ throw new IllegalStateException();
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.html b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.html
index a027d745f5..dd430486ca 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.html
@@ -1,5 +1,5 @@
<wicket:extend>
- <div wicket:id="authSource" class="mb-4"></div>
+ <div wicket:id="note" class="mb-4"></div>
<div wicket:id="content"></div>
<wicket:fragment wicket:id="authViaInternalDatabaseFrag">
<div class="alert alert-light alert-notice">This user is authenticating via internal database.
@@ -11,4 +11,7 @@
To authenticate via internal database, <a wicket:id="setPasswordForUser">set password for user</a> or <form wicket:id="tellUserToResetPassword" class="d-inline"><a wicket:id="tellUserToResetPassword">tell user to reset password</a></form>
</div>
</wicket:fragment>
+ <wicket:fragment wicket:id="serviceAccountFrag">
+ <div class="alert alert-light-warning alert-notice">This is a service account for task automation purpose</div>
+ </wicket:fragment>
</wicket:extend>
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.java
index 5978260a11..99ab7eeafe 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/profile/UserProfilePage.java
@@ -37,10 +37,12 @@ public class UserProfilePage extends UserPage {
protected void onInitialize() {
super.onInitialize();
- WebMarkupContainer authSourceContainer;
- if (getUser().getPassword() != null) {
- authSourceContainer = new Fragment("authSource", "authViaInternalDatabaseFrag", this);
- authSourceContainer.add(new Link<Void>("removePassword") {
+ WebMarkupContainer noteContainer;
+ if (getUser().isServiceAccount()) {
+ noteContainer = new Fragment("note", "serviceAccountFrag", this);
+ } else if (getUser().getPassword() != null) {
+ noteContainer = new Fragment("note", "authViaInternalDatabaseFrag", this);
+ noteContainer.add(new Link<Void>("removePassword") {
@Override
public void onClick() {
@@ -51,11 +53,11 @@ public class UserProfilePage extends UserPage {
}
}.add(new ConfirmClickModifier("Do you really want to remove password of this user?")));
} else {
- authSourceContainer = new Fragment("authSource", "authViaExternalSystemFrag", this);
- authSourceContainer.add(new BookmarkablePageLink<Void>("setPasswordForUser",
+ noteContainer = new Fragment("note", "authViaExternalSystemFrag", this);
+ noteContainer.add(new BookmarkablePageLink<Void>("setPasswordForUser",
UserPasswordPage.class, UserPasswordPage.paramsOf(getUser())));
var form = new Form<Void>("tellUserToResetPassword");
- authSourceContainer.add(form);
+ noteContainer.add(form);
var userId = getUser().getId();
form.add(new TaskButton("tellUserToResetPassword") {
@@ -98,7 +100,7 @@ public class UserProfilePage extends UserPage {
});
}
- add(authSourceContainer);
+ add(noteContainer);
add(new ProfileEditPanel("content", userModel));
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/querywatch/UserQueryWatchesPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/querywatch/UserQueryWatchesPage.java
index 7aab903690..e050a26397 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/querywatch/UserQueryWatchesPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/querywatch/UserQueryWatchesPage.java
@@ -14,6 +14,8 @@ public class UserQueryWatchesPage extends UserPage {
public UserQueryWatchesPage(PageParameters params) {
super(params);
+ if (getUser().isServiceAccount())
+ throw new IllegalStateException();
tabName = params.get(PARAM_TAB).toString(QueryWatchesPanel.TAB_ISSUE);
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/twofactorauthentication/UserTwoFactorAuthenticationPage.java b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/twofactorauthentication/UserTwoFactorAuthenticationPage.java
index c401896e5e..02b7817810 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/twofactorauthentication/UserTwoFactorAuthenticationPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/admin/usermanagement/twofactorauthentication/UserTwoFactorAuthenticationPage.java
@@ -10,6 +10,8 @@ public class UserTwoFactorAuthenticationPage extends UserPage {
public UserTwoFactorAuthenticationPage(PageParameters params) {
super(params);
+ if (getUser().isServiceAccount())
+ throw new IllegalStateException();
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
index 7b1790a18b..1540d54202 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/layout/LayoutPage.java
@@ -803,7 +803,10 @@ public abstract class LayoutPage extends BasePage {
if (loginUser != null) {
userInfo.add(new UserAvatar("avatar", loginUser));
userInfo.add(new Label("name", loginUser.getDisplayName()));
- if (loginUser.getEmailAddresses().isEmpty()) {
+ if (loginUser.isServiceAccount()) {
+ userInfo.add(new WebMarkupContainer("hasUnverifiedLink").setVisible(false));
+ userInfo.add(new WebMarkupContainer("noPrimaryAddressLink").setVisible(false));
+ } else if (loginUser.getEmailAddresses().isEmpty()) {
userInfo.add(new WebMarkupContainer("hasUnverifiedLink").setVisible(false));
userInfo.add(new ViewStateAwarePageLink<Void>("noPrimaryAddressLink", MyEmailAddressesPage.class));
} else if (loginUser.getEmailAddresses().stream().anyMatch(it->!it.isVerified())) {
@@ -823,15 +826,19 @@ public abstract class LayoutPage extends BasePage {
if (getPage() instanceof MyProfilePage)
item.add(AttributeAppender.append("class", "active"));
- userInfo.add(item = new ViewStateAwarePageLink<Void>("myEmailSetting", MyEmailAddressesPage.class));
- if (getPage() instanceof MyEmailAddressesPage)
- item.add(AttributeAppender.append("class", "active"));
+ if (getLoginUser() != null && !getLoginUser().isServiceAccount()) {
+ userInfo.add(item = new ViewStateAwarePageLink<Void>("myEmailSetting", MyEmailAddressesPage.class));
+ if (getPage() instanceof MyEmailAddressesPage)
+ item.add(AttributeAppender.append("class", "active"));
+ } else {
+ userInfo.add(new WebMarkupContainer("myEmailSetting").setVisible(false));
+ }
userInfo.add(item = new ViewStateAwarePageLink<Void>("myAvatar", MyAvatarPage.class));
if (getPage() instanceof MyAvatarPage)
item.add(AttributeAppender.append("class", "active"));
- if (loginUser != null && loginUser.getPassword() != null) {
+ if (loginUser != null && loginUser.getPassword() != null && !loginUser.isServiceAccount()) {
userInfo.add(item = new ViewStateAwarePageLink<Void>("myPassword", MyPasswordPage.class));
if (getPage() instanceof MyPasswordPage)
item.add(AttributeAppender.append("class", "active"));
@@ -855,20 +862,27 @@ public abstract class LayoutPage extends BasePage {
if (getPage() instanceof MyAccessTokensPage)
item.add(AttributeAppender.append("class", "active"));
- userInfo.add(item = new ViewStateAwarePageLink<Void>("myTwoFactorAuthentication", MyTwoFactorAuthenticationPage.class) {
- @Override
- protected void onConfigure() {
- super.onConfigure();
- setVisible(getLoginUser().isEnforce2FA());
- }
- });
- if (getPage() instanceof MyTwoFactorAuthenticationPage)
- item.add(AttributeAppender.append("class", "active"));
-
+ if (getLoginUser() != null && !getLoginUser().isServiceAccount()) {
+ userInfo.add(item = new ViewStateAwarePageLink<Void>("myTwoFactorAuthentication", MyTwoFactorAuthenticationPage.class) {
+ @Override
+ protected void onConfigure() {
+ super.onConfigure();
+ setVisible(getLoginUser().isEnforce2FA());
+ }
+ });
+ if (getPage() instanceof MyTwoFactorAuthenticationPage)
+ item.add(AttributeAppender.append("class", "active"));
+ } else {
+ userInfo.add(new WebMarkupContainer("myTwoFactorAuthentication").setVisible(false));
+ }
- userInfo.add(item = new ViewStateAwarePageLink<Void>("myQueryWatches", MyQueryWatchesPage.class));
- if (getPage() instanceof MyQueryWatchesPage)
- item.add(AttributeAppender.append("class", "active"));
+ if (getLoginUser() != null && !getLoginUser().isServiceAccount()) {
+ userInfo.add(item = new ViewStateAwarePageLink<Void>("myQueryWatches", MyQueryWatchesPage.class));
+ if (getPage() instanceof MyQueryWatchesPage)
+ item.add(AttributeAppender.append("class", "active"));
+ } else {
+ userInfo.add(new WebMarkupContainer("myQueryWatches").setVisible(false));
+ }
if (!SecurityUtils.isAnonymous(SecurityUtils.getPrevPrincipal())) {
Link<Void> signOutLink = new Link<Void>("signOut") {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/emailaddresses/MyEmailAddressesPage.java b/server-core/src/main/java/io/onedev/server/web/page/my/emailaddresses/MyEmailAddressesPage.java
index ed874f9d36..4e15e795ee 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/emailaddresses/MyEmailAddressesPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/emailaddresses/MyEmailAddressesPage.java
@@ -13,6 +13,8 @@ public class MyEmailAddressesPage extends MyPage {
public MyEmailAddressesPage(PageParameters params) {
super(params);
+ if (getLoginUser().isServiceAccount())
+ throw new IllegalStateException();
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/password/MyPasswordPage.java b/server-core/src/main/java/io/onedev/server/web/page/my/password/MyPasswordPage.java
index 017f47a1d6..263943d9db 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/password/MyPasswordPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/password/MyPasswordPage.java
@@ -13,6 +13,8 @@ public class MyPasswordPage extends MyPage {
public MyPasswordPage(PageParameters params) {
super(params);
+ if (getLoginUser().isServiceAccount())
+ throw new IllegalStateException();
if (getLoginUser().getPassword() == null)
throw new ExplicitException("Unable to change password as you are authenticating via external system");
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.html b/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.html
index 207225bba1..72c2f8b90e 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.html
@@ -1,5 +1,5 @@
<wicket:extend>
- <div wicket:id="authSource" class="mb-4"></div>
+ <div wicket:id="note" class="mb-4"></div>
<div wicket:id="content"></div>
<wicket:fragment wicket:id="authViaInternalDatabaseFrag">
<div class="alert alert-light alert-notice">You are authenticating via internal database</div>
@@ -7,4 +7,7 @@
<wicket:fragment wicket:id="authViaExternalSystemFrag">
<div class="alert alert-light-warning alert-notice">You are authenticating via external system</div>
</wicket:fragment>
+ <wicket:fragment wicket:id="serviceAccountFrag">
+ <div class="alert alert-light-warning alert-notice">You are a service account</div>
+ </wicket:fragment>
</wicket:extend>
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.java b/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.java
index 44aa055107..df907cef53 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/profile/MyProfilePage.java
@@ -19,10 +19,12 @@ public class MyProfilePage extends MyPage {
protected void onInitialize() {
super.onInitialize();
- if (getUser().getPassword() != null)
- add(new Fragment("authSource", "authViaInternalDatabaseFrag", this));
+ if (getUser().isServiceAccount())
+ add(new Fragment("note", "serviceAccountFrag", this));
+ else if (getUser().getPassword() != null)
+ add(new Fragment("note", "authViaInternalDatabaseFrag", this));
else
- add(new Fragment("authSource", "authViaExternalSystemFrag", this));
+ add(new Fragment("note", "authViaExternalSystemFrag", this));
add(new ProfileEditPanel("content", new AbstractReadOnlyModel<>() {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/querywatch/MyQueryWatchesPage.java b/server-core/src/main/java/io/onedev/server/web/page/my/querywatch/MyQueryWatchesPage.java
index 1917787cdd..ed289c6283 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/querywatch/MyQueryWatchesPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/querywatch/MyQueryWatchesPage.java
@@ -18,6 +18,8 @@ public class MyQueryWatchesPage extends MyPage {
public MyQueryWatchesPage(PageParameters params) {
super(params);
+ if (getLoginUser().isServiceAccount())
+ throw new IllegalStateException();
tabName = params.get(PARAM_TAB).toString(QueryWatchesPanel.TAB_ISSUE);
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/my/twofactorauthentication/MyTwoFactorAuthenticationPage.java b/server-core/src/main/java/io/onedev/server/web/page/my/twofactorauthentication/MyTwoFactorAuthenticationPage.java
index 31aef28e4e..054cacb1dd 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/my/twofactorauthentication/MyTwoFactorAuthenticationPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/my/twofactorauthentication/MyTwoFactorAuthenticationPage.java
@@ -12,6 +12,8 @@ public class MyTwoFactorAuthenticationPage extends MyPage {
public MyTwoFactorAuthenticationPage(PageParameters params) {
super(params);
+ if (getLoginUser().isServiceAccount())
+ throw new IllegalStateException();
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AbstractColumnPanel.java b/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AbstractColumnPanel.java
index 8cba594721..4cfc034f28 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AbstractColumnPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AbstractColumnPanel.java
@@ -1,5 +1,7 @@
package io.onedev.server.web.page.project.issues.boards;
+import java.util.HashSet;
+
import javax.annotation.Nullable;
import org.apache.wicket.Component;
@@ -120,7 +122,10 @@ abstract class AbstractColumnPanel extends Panel implements EditContext {
bean.setIterationPrefix(getIterationPrefix());
if (getIterationSelection().getIteration() != null)
bean.setCurrentIteration(getIterationSelection().getIteration().getName());
- new BeanEditModalPanel<>(target, bean) {
+ var excludeProperties = new HashSet<String>();
+ if (SecurityUtils.getUser().isServiceAccount())
+ excludeProperties.add(AddToIterationBean.PROP_SEND_NOTIFICATIONS);
+ new BeanEditModalPanel<>(target, bean, excludeProperties, true, null) {
@Override
protected String onSave(AjaxRequestTarget target, AddToIterationBean bean) {
@@ -155,7 +160,7 @@ abstract class AbstractColumnPanel extends Panel implements EditContext {
}
}));
} else {
- return new WebMarkupContainer(componentId);
+ return new WebMarkupContainer(componentId).setVisible(false);
}
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AddToIterationBean.java b/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AddToIterationBean.java
index b3ad7ea765..11d5c1d58a 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AddToIterationBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/issues/boards/AddToIterationBean.java
@@ -15,6 +15,7 @@ import java.util.List;
@Editable(name="Add Issues to Iteration")
public class AddToIterationBean implements Serializable {
+ public static final String PROP_SEND_NOTIFICATIONS = "sendNotifications";
private Long projectId;
private String iterationPrefix;
diff --git a/server-core/src/main/java/io/onedev/server/web/page/simple/security/PasswordResetPage.java b/server-core/src/main/java/io/onedev/server/web/page/simple/security/PasswordResetPage.java
index c6d9a3a5fd..788ba4052a 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/simple/security/PasswordResetPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/simple/security/PasswordResetPage.java
@@ -88,8 +88,12 @@ public class PasswordResetPage extends SimplePage {
protected TaskResult runTask(TaskLogger logger) {
return OneDev.getInstance(SessionManager.class).call(() -> {
User user = getUserManager().findByName(loginNameOrEmail);
- if (user == null)
+ if (user != null) {
+ if (user.isServiceAccount())
+ throw new ExplicitException("Can not reset password for service account");
+ } else {
user = getUserManager().findByVerifiedEmailAddress(loginNameOrEmail);
+ }
if (user == null) {
throw new ExplicitException("No user found with login name or verified email: " + loginNameOrEmail);
} else if (user.getPassword() == null) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/simple/security/SignUpPage.java b/server-core/src/main/java/io/onedev/server/web/page/simple/security/SignUpPage.java
index d68042f3e9..7f56c9b69f 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/simple/security/SignUpPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/simple/security/SignUpPage.java
@@ -52,7 +52,7 @@ public class SignUpPage extends SimplePage {
super.onInitialize();
SignUpBean bean = new SignUpBean();
- BeanEditor editor = BeanContext.edit("editor", bean, Sets.newHashSet(PROP_NOTIFY_OWN_EVENTS), true);
+ BeanEditor editor = BeanContext.edit("editor", bean, Sets.newHashSet(PROP_SERVICE_ACCOUNT, PROP_NOTIFY_OWN_EVENTS), true);
Form<?> form = new Form<Void>("form") {
diff --git a/server-core/src/main/java/io/onedev/server/web/util/editbean/NewUserBean.java b/server-core/src/main/java/io/onedev/server/web/util/editbean/NewUserBean.java
index 03f5f08c4e..bf96c87b98 100644
--- a/server-core/src/main/java/io/onedev/server/web/util/editbean/NewUserBean.java
+++ b/server-core/src/main/java/io/onedev/server/web/util/editbean/NewUserBean.java
@@ -3,8 +3,9 @@ package io.onedev.server.web.util.editbean;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
-import io.onedev.server.model.User;
import io.onedev.server.annotation.Editable;
+import io.onedev.server.annotation.ShowCondition;
+import io.onedev.server.model.User;
@Editable
public class NewUserBean extends User {
@@ -16,6 +17,7 @@ public class NewUserBean extends User {
private String emailAddress;
@Editable(order=1000)
+ @ShowCondition("isServiceAccountDisabled")
@NotEmpty
@Email
public String getEmailAddress() {