Commit graph

79 commits

Author SHA1 Message Date
Earl Warren 7cabc5670d
Implement remote user login source and promotion to regular user
A remote user (UserTypeRemoteUser) is a placeholder that can be
promoted to a regular user (UserTypeIndividual). It represents users
that exist somewhere else. Although the UserTypeRemoteUser already
exists in Forgejo, it is neither used or documented.

A new login type / source (Remote) is introduced and set to be the login type
of remote users.

Type        UserTypeRemoteUser
LogingType  Remote

The association between a remote user and its counterpart in another
environment (for instance another forge) is via the OAuth2 login
source:

LoginName   set to the unique identifier relative to the login source
LoginSource set to the identifier of the remote source

For instance when migrating from GitLab.com, a user can be created as
if it was authenticated using GitLab.com as an OAuth2 authentication
source.

When a user authenticates to Forejo from the same authentication
source and the identifier match, the remote user is promoted to a
regular user. For instance if 43 is the ID of the GitLab.com OAuth2
login source, 88 is the ID of the Remote loging source, and 48323
is the identifier of the foo user:

Type        UserTypeRemoteUser
LogingType  Remote
LoginName   48323
LoginSource 88
Email       (empty)
Name        foo

Will be promoted to the following when the user foo authenticates to
the Forgejo instance using GitLab.com as an OAuth2 provider. All users
with a LoginType of Remote and a LoginName of 48323 are examined. If
the LoginSource has a provider name that matches the provider name of
GitLab.com (usually just "gitlab"), it is a match and can be promoted.

The email is obtained via the OAuth2 provider and the user set to:

Type        UserTypeIndividual
LogingType  OAuth2
LoginName   48323
LoginSource 43
Email       foo@example.com
Name        foo

Note: the Remote login source is an indirection to the actual login
source, i.e. the provider string my be set to a login source that does
not exist yet.
2024-04-25 13:03:49 +02:00
Jack Hay e08f05b069
Add setting to disable user features when user login type is not plain (#29615)
- Adds setting `EXTERNAL_USER_DISABLE_FEATURES` to disable any supported
user features when login type is not plain
- In general, this is necessary for SSO implementations to avoid
inconsistencies between the external account management and the linked
account
- Adds helper functions to encourage correct use

(cherry picked from commit 59d4aadba5c15d02f3b9f0e61abb7476870c20a5)

Conflicts:
	- docs/content/administration/config-cheat-sheet.en-us.md
          Removed.
	- modules/setting/admin.go
          Trivial resolution: pick the newly added struct member.
2024-04-07 11:09:21 +02:00
hazycora f8e48e066a
add pronoun field to user profiles 2024-04-03 15:11:17 -05:00
Gergely Nagy 36147f580c
Allow users to hide all "Add more units..." hints
Repositories displaying an "Add more..." tab on the header is a neat way
to let people discover they can enable more units. However, displaying
it all the time for repository owners, even when they deliberately do
not want to enable more units gets noisy very fast.

As such, this patch introduces a new setting which lets people disable
this hint under the appearance settings.

Fixes #2378.

Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu>
2024-03-21 08:15:51 +01:00
pengqiseven e825d007b1
remove repetitive words (#29695)
Signed-off-by: pengqiseven <912170095@qq.com>
(cherry picked from commit 7f856d5d742dcb6febdb8a3f22cd9a8fecc69a4d)
2024-03-20 08:46:28 +01:00
Zettat123 b6057a34db
Skip email domain check when admin users adds user manually (#29522)
Fix #27457

Administrators should be able to manually create any user even if the
user's email address is not in `EMAIL_DOMAIN_ALLOWLIST`.

(cherry picked from commit 4fd9c56ed09b31e2f6164a5f534a31c6624d0478)
2024-03-11 23:36:58 +07:00
6543 e2371743d5
remove util.OptionalBool and related functions (#29513)
and migrate affected code

_last refactoring bits to replace **util.OptionalBool** with
**optional.Option[bool]**_

(cherry picked from commit a3f05d0d98408bb47333b19f505b21afcefa9e7c)

Conflicts:
	services/repository/branch.go
	trivial context conflict
2024-03-06 12:10:46 +08:00
6543 8ff858b94b
Start to migrate from util.OptionalBool to optional.Option[bool] (#29329)
just create transition helper and migrate two structs

(cherry picked from commit 7fbdb60fc1152acc9a040dc04b1b0f5a3475b081)
2024-02-26 22:30:26 +01:00
KN4CK3R 52ef33b931
Remove unused KeyID. (#29167)
`KeyID` is never set.

(cherry picked from commit 155269fa586c41a268530c3bb56349e68e6761d7)

Conflicts:
	models/user/email_address.go
	trivial context conflict
2024-02-16 15:20:52 +01:00
Gwyneth Morgan 9a1d5c549c
[gitea] Drop "@" from email sender to avoid spam filters (#29109)
Commit 360b3fd17c (Include username in email headers (#28981),
2024-02-03) adds usernames to the From field of notification emails in
the form of `Display Name (@username)`, to prevent spoofing. However,
some email filtering software flags "@" in the display name part of the
From field as potential spoofing, as you could set the display name part
to another email address than the one you are sending from (e.g.
`From: "apparent@email-address" <actual@email-address>`). To avoid
being flagged, instead send emails from `Display Name (username)`.

Closes: #29107

---------

Co-authored-by: Giteabot <teabot@gitea.io>
(cherry picked from commit 5b2fd0fc19a2a77414c8e2989b4794b6617221f5)
2024-02-11 13:47:44 +01:00
Earl Warren 094c84ed6d
Merge branch 'rebase-forgejo-dependency' into wip-forgejo 2024-02-05 18:58:23 +01:00
Aravinth Manivannan 2d06901a18
[GITEA] notifies admins on new user registration
Sends email with information on the new user (time of creation and time of last sign-in) and a link to manage the new user from the admin panel

closes: https://codeberg.org/forgejo/forgejo/issues/480

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/1371
Co-authored-by: Aravinth Manivannan <realaravinth@batsense.net>
Co-committed-by: Aravinth Manivannan <realaravinth@batsense.net>
(cherry picked from commit c721aa828b)
(cherry picked from commit 6487efcb9d)

Conflicts:
	modules/notification/base/notifier.go
	modules/notification/base/null.go
	modules/notification/notification.go
	https://codeberg.org/forgejo/forgejo/pulls/1422
(cherry picked from commit 7ea66ee1c5)

Conflicts:
	services/notify/notifier.go
	services/notify/notify.go
	services/notify/null.go
	https://codeberg.org/forgejo/forgejo/pulls/1469
(cherry picked from commit 7d2d997011)
(cherry picked from commit 435a54f140)
(cherry picked from commit 8ec7b3e448)

[GITEA] notifies admins on new user registration (squash) performance bottleneck

Refs: https://codeberg.org/forgejo/forgejo/issues/1479
(cherry picked from commit 97ac9147ff)
(cherry picked from commit 19f295c16b)
(cherry picked from commit 3367dcb2cf)

[GITEA] notifies admins on new user registration (squash) cosmetic changes

Co-authored-by: delvh <dev.lh@web.de>
(cherry picked from commit 9f1670e040)
(cherry picked from commit de5bb2a224)
(cherry picked from commit 8f8e52f31a)
(cherry picked from commit e0d5130312)
(cherry picked from commit f1288d6d9b)
(cherry picked from commit 1db4736fd7)
(cherry picked from commit e8dcbb6cd6)
(cherry picked from commit 09625d6476)

[GITEA] notifies admins on new user registration (squash) ctx.Locale

(cherry picked from commit dab7212fad)
(cherry picked from commit 9b7bbae8c4)
(cherry picked from commit f750b71d3d)
(cherry picked from commit f79af36679)
(cherry picked from commit e76eee334e)

[GITEA] notifies admins on new user registration (squash) fix locale

(cherry picked from commit 54cd100d8d)
(cherry picked from commit 053dbd3d50)

[GITEA] notifies admins on new user registration (squash) fix URL

1. Use absolute URL in the admin panel link sent on new registrations
2. Include absolute URL of the newly signed-up user's profile.

New email looks like this:

<details><summary>Please click to expand</summary>

```
--153937b1864f158f4fd145c4b5d4a513568681dd489021dd466a8ad7b770
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=UTF-8

User Information: @realaravinth ( http://localhost:3000/realaravinth )
----------------------------------------------------------------------

* Created: 2023-12-13 19:36:50 +05:30

Please click here ( http://localhost:3000/admin/users/9 ) to manage the use=
r from the admin panel.
--153937b1864f158f4fd145c4b5d4a513568681dd489021dd466a8ad7b770
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=UTF-8

<!DOCTYPE html>
<html>
<head>
	<meta http-equiv=3D"Content-Type" content=3D"text/html; charset=3Dutf-8">
	<title>New user realaravinth just signed up</title>

	<style>
		blockquote { padding-left: 1em; margin: 1em 0; border-left: 1px solid gre=
y; color: #777}
		.footer { font-size:small; color:#666;}
	</style>

</head>

<body>
	<ul>
		<h3>User Information: <a href=3D"http://localhost:3000/realaravinth">@rea=
laravinth</a></h3>
		<li>Created: <relative-time format=3D"datetime" weekday=3D"" year=3D"nume=
ric" month=3D"short" day=3D"numeric" hour=3D"numeric" minute=3D"numeric" se=
cond=3D"numeric" datetime=3D"2023-12-13T19:36:50+05:30">2023-12-13 19:36:50=
 +05:30</relative-time></li>
	</ul>
	<p> Please <a href=3D"http://localhost:3000/admin/users/9" rel=3D"nofollow=
">click here</a> to manage the user from the admin panel. </p>
</body>
</html>

--153937b1864f158f4fd145c4b5d4a513568681dd489021dd466a8ad7b770--
```

</details>

fixes: https://codeberg.org/forgejo/forgejo/issues/1927
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/1940
Reviewed-by: Earl Warren <earl-warren@noreply.codeberg.org>
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Co-authored-by: Aravinth Manivannan <realaravinth@batsense.net>
Co-committed-by: Aravinth Manivannan <realaravinth@batsense.net>
(cherry picked from commit b8d764e36a)
(cherry picked from commit d48b84f623)

Conflicts:
	routers/web/auth/auth.go
	https://codeberg.org/forgejo/forgejo/pulls/2034
(cherry picked from commit 02d3c125cc)
(cherry picked from commit 367374ecc3)

Conflicts:
	models/user/user_test.go
	https://codeberg.org/forgejo/forgejo/pulls/2119
(cherry picked from commit 4124fa5aa4)
(cherry picked from commit 7f12610ff6)

[GITEA] notifies admins on new user registration (squash) DeleteByID

trivial conflict because of
   778ad795fd Refactor deletion (#28610)

(cherry picked from commit 05682614e5)
(cherry picked from commit 64bd374803)
(cherry picked from commit 63d086f666)
(cherry picked from commit 3cd48ef4d5)

Conflicts:
	options/locale/locale_en-US.ini
	https://codeberg.org/forgejo/forgejo/pulls/2249
(cherry picked from commit 6578ec4ed6)

Conflicts:
	routers/web/auth/auth.go
	https://codeberg.org/forgejo/forgejo/pulls/2300
2024-02-05 16:09:28 +01:00
Loïc Dachary ef25d18d9c
[BRANDING] reserve forgejo-actions username
(cherry picked from commit 2a25be788b)
(cherry picked from commit b270d5815c)
(cherry picked from commit e7382cc71e)
(cherry picked from commit 665400ea1e)
(cherry picked from commit f5b2c691f1)
(cherry picked from commit 3df97adfef)
(cherry picked from commit 494f6eafc1)
(cherry picked from commit 822e3d2c83)
(cherry picked from commit 7460f12568)
(cherry picked from commit f6cd70881e)
(cherry picked from commit c669ce8173)
(cherry picked from commit 1d5a433e02)
(cherry picked from commit c1a4dc150c)
(cherry picked from commit dd1c971c6c)
(cherry picked from commit 8d2dcd9b1e)
(cherry picked from commit b6bb8fd275)
(cherry picked from commit d4b71fe96e)
(cherry picked from commit e204ec0b23)
(cherry picked from commit 8d9f1174bd)
(cherry picked from commit e314a7d5ba)
(cherry picked from commit 48b3ad5a30)
(cherry picked from commit 71ed4b7c69)
(cherry picked from commit d63324ccb6)
(cherry picked from commit 9249e893db)
(cherry picked from commit 78f156427b)
(cherry picked from commit c3d4a1a602)
(cherry picked from commit 83b1855f55)
(cherry picked from commit 319815d9b1)
(cherry picked from commit c4fcbfd297)
(cherry picked from commit fb58c85222)
(cherry picked from commit 69c24e3e8b)
(cherry picked from commit 1e9ec4737a)
(cherry picked from commit 70439970c1)
(cherry picked from commit 7e6146c1a8)
(cherry picked from commit 7adf6d5869)
(cherry picked from commit 8985e17343)
(cherry picked from commit fd4dc3ebca)
(cherry picked from commit d31bf1639e)
(cherry picked from commit d2a9b6dea0)
(cherry picked from commit 0d9279bc85)
(cherry picked from commit 0591a15cee)
(cherry picked from commit 3ad88f1146)
(cherry picked from commit 5501f5b2e5)
(cherry picked from commit 9b9f62f774)
(cherry picked from commit dd2e5f525d)
(cherry picked from commit 9b489fd8a5)
(cherry picked from commit 60c820562a)
(cherry picked from commit 084d732317)
(cherry picked from commit e1bb077d6e)
2024-02-05 16:05:01 +01:00
Gusted c6a53c3172
[SECURITY] Rework long-term authentication
- This is a 'front-port' of the already existing patch on v1.21 and
v1.20, but applied on top of what Gitea has done to rework the LTA
mechanism. Forgejo will stick with the reworked mechanism by the Forgejo
Security team for the time being. The removal of legacy code (AES-GCM) has been
left out.
- The current architecture is inherently insecure, because you can
construct the 'secret' cookie value with values that are available in
the database. Thus provides zero protection when a database is
dumped/leaked.
- This patch implements a new architecture that's inspired from: [Paragonie Initiative](https://paragonie.com/blog/2015/04/secure-authentication-php-with-long-term-persistence#secure-remember-me-cookies).
- Integration testing is added to ensure the new mechanism works.
- Removes a setting, because it's not used anymore.

(cherry picked from commit e3d6622a63)
(cherry picked from commit fef1a6dac5)
(cherry picked from commit b0c5165145)
(cherry picked from commit 7ad51b9f8d)
(cherry picked from commit 64f053f383)
(cherry picked from commit f5e78e4c20)

Conflicts:
	services/auth/auth_token_test.go
	https://codeberg.org/forgejo/forgejo/pulls/2069
(cherry picked from commit f69fc23d4b)
(cherry picked from commit d955ab3ab0)
(cherry picked from commit 9220088f90)
(cherry picked from commit c73ac63696)
(cherry picked from commit 747a176048)

Conflicts:
	models/user/user.go
	routers/web/user/setting/account.go
	https://codeberg.org/forgejo/forgejo/pulls/2295
2024-02-05 15:06:15 +01:00
KN4CK3R f8b471ace1
Unify user update methods (#28733)
Fixes #28660
Fixes an admin api bug related to `user.LoginSource`
Fixed `/user/emails` response not identical to GitHub api

This PR unifies the user update methods. The goal is to keep the logic
only at one place (having audit logs in mind). For example, do the
password checks only in one method not everywhere a password is updated.

After that PR is merged, the user creation should be next.
2024-02-04 13:29:09 +00:00
Gwyneth Morgan 360b3fd17c
Include username in email headers (#28981)
Emails from Gitea comments do not contain the username of the commenter
anywhere, only their display name, so it is not possible to verify who
made a comment from the email itself:

	From: "Alice" <email@gitea>
	X-Gitea-Sender: Alice
	X-Gitea-Recipient: Bob
	X-GitHub-Sender: Alice
	X-GitHub-Recipient: Bob

	This comment looks like it's from @alice.

The X-Gitea/X-GitHub headers also use display names, which is not very
reliable for filtering, and inconsistent with GitHub's behavior:

	X-GitHub-Sender: lunny
	X-GitHub-Recipient: gwymor

This change includes both the display name and username in the From
header, and switches the other headers from display name to username:

	From: "Alice (@fakealice)" <email@gitea>
	X-Gitea-Sender: fakealice
	X-Gitea-Recipient: bob
	X-GitHub-Sender: fakealice
	X-GitHub-Recipient: bob

	This comment looks like it's from @alice.
2024-02-03 00:41:27 +00:00
yp05327 ce0225c1b8
Forbid removing the last admin user (#28337)
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2024-01-15 06:51:43 +00:00
yp05327 b820019fec
Fix when private user following user, private user will not be counted in his own view (#28037)
Doer: asdasasdasasdasasdasasdasasdasasdasasdas (private user)
Followed: TestUser (public user)

Before:
(From doer's view)

![image](https://github.com/go-gitea/gitea/assets/18380374/9ba16b3b-068c-43c5-a3dd-e3343b5b32f2)
(From followed user's view, can see doer)

![image](https://github.com/go-gitea/gitea/assets/18380374/dfd1b564-d689-4393-b3d3-1e6bf52c94ba)

After:
(From doer's view)

![image](https://github.com/go-gitea/gitea/assets/18380374/1c85c1d1-c9f7-40c8-948c-145f7cae9a04)
2024-01-15 05:43:14 +00:00
Kyle D 54acf7b0d4
Normalize oauth email username (#28561) 2024-01-03 18:48:20 -06:00
Nanguan Lin 881806a50b
Replace -1 with GhostUserID (#27703) 2023-10-20 14:43:08 +00:00
24601 624c0ba920
fix: comment typo (#27388)
fix a typo in the comment
2023-10-02 08:31:03 +00:00
JakobDev f91dbbba98
Next round of db.DefaultContext refactor (#27089)
Part of #27065
2023-09-16 14:39:12 +00:00
JakobDev 76659b1114
Reduce usage of db.DefaultContext (#27073)
Part of #27065

This reduces the usage of `db.DefaultContext`. I think I've got enough
files for the first PR. When this is merged, I will continue working on
this.

Considering how many files this PR affect, I hope it won't take to long
to merge, so I don't end up in the merge conflict hell.

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2023-09-14 17:09:32 +00:00
JakobDev ea385f5d39
Fix API leaking Usermail if not logged in (#25097)
The API should only return the real Mail of a User, if the caller is
logged in. The check do to this don't work. This PR fixes this. This not
really a security issue, but can lead to Spam.

---------

Co-authored-by: silverwind <me@silverwind.io>
2023-07-31 01:18:38 +00:00
puni9869 2af30f715e
Fix inconsistent user profile layout across tabs (#25625)
Fix ::User Profile Page  Project Tab Have Inconsistent Layout and Style
Added the big_avator for consistency in the all header_items tabs.
Fixes: #24871
> ### Description
> in the user profile page the `Packages` and `Projects` tab have small
icons for user but other tabs have bigger profile picture with user
info:
> 
> ### Screenshots
> ### **For Packages And Projects:**
>
![image](https://user-images.githubusercontent.com/25511175/240148601-2420d77b-ba25-4718-9ccb-c5d0d95e3079.png)
> 
> ### **For Other Tabs:**
>
![image](https://user-images.githubusercontent.com/25511175/240148461-ce9636b3-fe11-4c46-a230-30d83eee5947.png)
> 

## Before

![image](https://github.com/go-gitea/gitea/assets/80308335/975ad038-07ca-4b10-b75d-ccf259be7b9d)


 ## After changes
Project View 
<img width="1394" alt="image"
src="https://github.com/go-gitea/gitea/assets/80308335/95d181d7-8e61-496d-9899-7b825c91ad56">


Packages View
<img width="1378" alt="image"
src="https://github.com/go-gitea/gitea/assets/80308335/7f5fd60f-6b18-4fa8-8c56-7b0d45d1a610">


## Org view for projects page
<img width="1385" alt="image"
src="https://github.com/go-gitea/gitea/assets/80308335/6400dc89-a5ae-4f0a-831b-5b6efa020d89">

## Org view for packages page
<img width="1387" alt="image"
src="https://github.com/go-gitea/gitea/assets/80308335/4e1e9ffe-1e4b-4334-8657-de11b5fd31d0">

---------

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Giteabot <teabot@gitea.io>
Co-authored-by: silverwind <me@silverwind.io>
2023-07-06 18:59:24 +00:00
Lunny Xiao 6e19484f4d
Sync branches into databases (#22743)
Related #14180
Related #25233 
Related #22639
Close #19786
Related #12763 

This PR will change all the branches retrieve method from reading git
data to read database to reduce git read operations.

- [x] Sync git branches information into database when push git data
- [x] Create a new table `Branch`, merge some columns of `DeletedBranch`
into `Branch` table and drop the table `DeletedBranch`.
- [x] Read `Branch` table when visit `code` -> `branch` page
- [x] Read `Branch` table when list branch names in `code` page dropdown
- [x] Read `Branch` table when list git ref compare page
- [x] Provide a button in admin page to manually sync all branches.
- [x] Sync branches if repository is not empty but database branches are
empty when visiting pages with branches list
- [x] Use `commit_time desc` as the default FindBranch order by to keep
consistent as before and deleted branches will be always at the end.

---------

Co-authored-by: Jason Song <i@wolfogre.com>
2023-06-29 10:03:20 +00:00
Yarden Shoham abccb86b36
Show bot label next to username when rendering autor link if the user is a bot (#24943)
If the user is a bot, we'll add a label next to the author link that
says `bot`. I didn't localize `bot` because passing `locale` into the
`autorlink` template would require changing all calls.

# Example
`yardenshoham` is a bot.
## Before

![image](https://github.com/go-gitea/gitea/assets/20454870/77390780-b763-4f0f-b358-bbccdbf17a5d)

## After

![image](https://github.com/go-gitea/gitea/assets/20454870/72af342f-ee76-4337-95ad-4ecaba853fed)

---------

Signed-off-by: Yarden Shoham <git@yardenshoham.com>
2023-05-26 18:58:11 +02:00
谈笑风生间 309354c70e
New webhook trigger for receiving Pull Request review requests (#24481)
close https://github.com/go-gitea/gitea/issues/16321

Provided a webhook trigger for requesting someone to review the Pull
Request.

Some modifications have been made to the returned `PullRequestPayload`
based on the GitHub webhook settings, including:
- add a description of the current reviewer object as
`RequestedReviewer` .
- setting the action to either **review_requested** or
**review_request_removed** based on the operation.
- adding the `RequestedReviewers` field to the issues_model.PullRequest.
This field will be loaded into the PullRequest through
`LoadRequestedReviewers()` when `ToAPIPullRequest` is called.

After the Pull Request is merged, I will supplement the relevant
documentation.
2023-05-24 22:06:27 -04:00
Lunny Xiao a523bd5889
Only validate changed columns when update user (#24867)
Fix #23211
Replace #23496
2023-05-24 07:30:55 +00:00
wxiaoguang 4647660776
Rewrite logger system (#24726)
## ⚠️ Breaking

The `log.<mode>.<logger>` style config has been dropped. If you used it,
please check the new config manual & app.example.ini to make your
instance output logs as expected.

Although many legacy options still work, it's encouraged to upgrade to
the new options.

The SMTP logger is deleted because SMTP is not suitable to collect logs.

If you have manually configured Gitea log options, please confirm the
logger system works as expected after upgrading.

## Description

Close #12082 and maybe more log-related issues, resolve some related
FIXMEs in old code (which seems unfixable before)

Just like rewriting queue #24505 : make code maintainable, clear legacy
bugs, and add the ability to support more writers (eg: JSON, structured
log)

There is a new document (with examples): `logging-config.en-us.md`

This PR is safer than the queue rewriting, because it's just for
logging, it won't break other logic.

## The old problems

The logging system is quite old and difficult to maintain:
* Unclear concepts: Logger, NamedLogger, MultiChannelledLogger,
SubLogger, EventLogger, WriterLogger etc
* Some code is diffuclt to konw whether it is right:
`log.DelNamedLogger("console")` vs `log.DelNamedLogger(log.DEFAULT)` vs
`log.DelLogger("console")`
* The old system heavily depends on ini config system, it's difficult to
create new logger for different purpose, and it's very fragile.
* The "color" trick is difficult to use and read, many colors are
unnecessary, and in the future structured log could help
* It's difficult to add other log formats, eg: JSON format
* The log outputer doesn't have full control of its goroutine, it's
difficult to make outputer have advanced behaviors
* The logs could be lost in some cases: eg: no Fatal error when using
CLI.
* Config options are passed by JSON, which is quite fragile.
* INI package makes the KEY in `[log]` section visible in `[log.sub1]`
and `[log.sub1.subA]`, this behavior is quite fragile and would cause
more unclear problems, and there is no strong requirement to support
`log.<mode>.<logger>` syntax.


## The new design

See `logger.go` for documents.


## Screenshot

<details>


![image](https://github.com/go-gitea/gitea/assets/2114189/4462d713-ba39-41f5-bb08-de912e67e1ff)


![image](https://github.com/go-gitea/gitea/assets/2114189/b188035e-f691-428b-8b2d-ff7b2199b2f9)


![image](https://github.com/go-gitea/gitea/assets/2114189/132e9745-1c3b-4e00-9e0d-15eaea495dee)

</details>

## TODO

* [x] add some new tests
* [x] fix some tests
* [x] test some sub-commands (manually ....)

---------

Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-05-21 22:35:11 +00:00
Lunny Xiao c59a057297
Refactor rename user and rename organization (#24052)
This PR is a refactor at the beginning. And now it did 4 things.
- [x] Move renaming organizaiton and user logics into services layer and
merged as one function
- [x] Support rename a user capitalization only. For example, rename the
user from `Lunny` to `lunny`. We just need to change one table `user`
and others should not be touched.
- [x] Before this PR, some renaming were missed like `agit`
- [x] Fix bug the API reutrned from `http.StatusNoContent` to `http.StatusOK`
2023-05-21 23:13:47 +08:00
yp05327 cc64a92560
Add follow organization and fix the logic of following page (#24345)
![image](https://user-images.githubusercontent.com/18380374/234740589-066f2e5c-30c7-4fc3-a539-066100e1f138.png)

![image](https://user-images.githubusercontent.com/18380374/234740605-88efe55d-7eaa-422e-ab86-0b5a402ca11c.png)

Maybe we can fix user card tmpl in #24319?
Or maybe a list is better here

![image](https://user-images.githubusercontent.com/18380374/234451417-7f93df20-4b19-4abb-a62d-4c67e1aa2220.png)

---------

Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: Giteabot <teabot@gitea.io>
2023-04-29 15:13:58 -04:00
Infinoid 949ba4894b
Fix comment for EmailNotificationsAndYourOwn constant (#24236)
This fixes some copypasta in the constant definitions for the
`User.EmailNotificationsPreference` field. No code changes.
2023-04-21 10:27:32 -04:00
techknowlogick 1819c4b59b
Add new user types reserved, bot, and remote (#24026)
This allows for usernames, and emails connected to them to be reserved
and not reused.

Use case, I manage an instance with open registration, and sometimes
when users are deleted for spam (or other purposes), their usernames are
freed up and they sign up again with the same information.

This could also be used to reserve usernames, and block them from being
registered (in case an instance would like to block certain things
without hardcoding the list in code and compiling from scratch).

This is an MVP, that will allow for future work where you can set
something as reserved via the interface.

---------

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2023-04-17 12:36:50 -04:00
6543 2b91841cd3
Reserve ".png" suffix for user/org names (#23992)
Org/User names ending with ".png" where not functional, so reserve them

alternative / close  #23908
2023-04-10 16:14:16 -04:00
techknowlogick 03591f0f95
add user rename endpoint to admin api (#22789)
this is a simple endpoint that adds the ability to rename users to the
admin API.

Note: this is not in a mergeable state. It would be better if this was
handled by a PATCH/POST to the /api/v1/admin/users/{username} endpoint
and the username is modified.

---------

Co-authored-by: Jason Song <i@wolfogre.com>
2023-03-14 03:45:21 -04:00
yp05327 cf29ee6dd2
Add missing tabs to org projects page (#22705)
Fixes https://github.com/go-gitea/gitea/issues/22676

Context Data `IsOrganizationMember` and `IsOrganizationOwner` is used to
control the visibility of `people` and `team` tab.

2871ea0809/templates/org/menu.tmpl (L19-L40)

And because of the reuse of user projects page, User Context is changed
to Organization Context. But the value of `IsOrganizationMember` and
`IsOrganizationOwner` are not being given.

I reused func `HandleOrgAssignment` to add them to the ctx, but may have
some unnecessary variables, idk whether it is ok.

I found there is a missing `PageIsViewProjects` at create project page.
2023-03-10 09:18:20 -06:00
zeripath 61b89747ed
Provide the ability to set password hash algorithm parameters (#22942)
This PR refactors and improves the password hashing code within gitea
and makes it possible for server administrators to set the password
hashing parameters

In addition it takes the opportunity to adjust the settings for `pbkdf2`
in order to make the hashing a little stronger.

The majority of this work was inspired by PR #14751 and I would like to
thank @boppy for their work on this.

Thanks to @gusted for the suggestion to adjust the `pbkdf2` hashing
parameters.

Close #14751

---------

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2023-02-19 15:35:20 +08:00
Sybren aa45777c92
Allow custom "created" timestamps in user creation API (#22549)
Allow back-dating user creation via the `adminCreateUser` API operation.
`CreateUserOption` now has an optional field `created_at`, which can
contain a datetime-formatted string. If this field is present, the
user's `created_unix` database field will be updated to its value.

This is important for Blender's migration of users from Phabricator to
Gitea. There are many users, and the creation timestamp of their account
can give us some indication as to how long someone's been part of the
community.

The back-dating is done in a separate query that just updates the user's
`created_unix` field. This was the easiest and cleanest way I could
find, as in the initial `INSERT` query the field always is set to "now".
2023-02-16 10:32:01 -06:00
Lunny Xiao bd820aa9c5
Add context cache as a request level cache (#22294)
To avoid duplicated load of the same data in an HTTP request, we can set
a context cache to do that. i.e. Some pages may load a user from a
database with the same id in different areas on the same page. But the
code is hidden in two different deep logic. How should we share the
user? As a result of this PR, now if both entry functions accept
`context.Context` as the first parameter and we just need to refactor
`GetUserByID` to reuse the user from the context cache. Then it will not
be loaded twice on an HTTP request.

But of course, sometimes we would like to reload an object from the
database, that's why `RemoveContextData` is also exposed.

The core context cache is here. It defines a new context
```go
type cacheContext struct {
	ctx  context.Context
	data map[any]map[any]any
        lock sync.RWMutex
}

var cacheContextKey = struct{}{}

func WithCacheContext(ctx context.Context) context.Context {
	return context.WithValue(ctx, cacheContextKey, &cacheContext{
		ctx:  ctx,
		data: make(map[any]map[any]any),
	})
}
```

Then you can use the below 4 methods to read/write/del the data within
the same context.

```go
func GetContextData(ctx context.Context, tp, key any) any
func SetContextData(ctx context.Context, tp, key, value any)
func RemoveContextData(ctx context.Context, tp, key any)
func GetWithContextCache[T any](ctx context.Context, cacheGroupKey string, cacheTargetID any, f func() (T, error)) (T, error)
```

Then let's take a look at how `system.GetString` implement it.

```go
func GetSetting(ctx context.Context, key string) (string, error) {
	return cache.GetWithContextCache(ctx, contextCacheKey, key, func() (string, error) {
		return cache.GetString(genSettingCacheKey(key), func() (string, error) {
			res, err := GetSettingNoCache(ctx, key)
			if err != nil {
				return "", err
			}
			return res.SettingValue, nil
		})
	})
}
```

First, it will check if context data include the setting object with the
key. If not, it will query from the global cache which may be memory or
a Redis cache. If not, it will get the object from the database. In the
end, if the object gets from the global cache or database, it will be
set into the context cache.

An object stored in the context cache will only be destroyed after the
context disappeared.
2023-02-15 21:37:34 +08:00
Jason Song 4011821c94
Implement actions (#21937)
Close #13539.

Co-authored by: @lunny @appleboy @fuxiaohei and others.

Related projects:
- https://gitea.com/gitea/actions-proto-def
- https://gitea.com/gitea/actions-proto-go
- https://gitea.com/gitea/act
- https://gitea.com/gitea/act_runner

### Summary

The target of this PR is to bring a basic implementation of "Actions",
an internal CI/CD system of Gitea. That means even though it has been
merged, the state of the feature is **EXPERIMENTAL**, and please note
that:

- It is disabled by default;
- It shouldn't be used in a production environment currently;
- It shouldn't be used in a public Gitea instance currently;
- Breaking changes may be made before it's stable.

**Please comment on #13539 if you have any different product design
ideas**, all decisions reached there will be adopted here. But in this
PR, we don't talk about **naming, feature-creep or alternatives**.

### ⚠️ Breaking

`gitea-actions` will become a reserved user name. If a user with the
name already exists in the database, it is recommended to rename it.

### Some important reviews

- What is `DEFAULT_ACTIONS_URL` in `app.ini` for?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1055954954
- Why the api for runners is not under the normal `/api/v1` prefix?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1061173592
- Why DBFS?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1061301178
- Why ignore events triggered by `gitea-actions` bot?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1063254103
- Why there's no permission control for actions?
  - https://github.com/go-gitea/gitea/pull/21937#discussion_r1090229868

### What it looks like

<details>

#### Manage runners

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205870657-c72f590e-2e08-4cd4-be7f-2e0abb299bbf.png">

#### List runs

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205872794-50fde990-2b45-48c1-a178-908e4ec5b627.png">


#### View logs

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205872501-9b7b9000-9542-4991-8f55-18ccdada77c3.png">



</details>

### How to try it

<details>

#### 1. Start Gitea

Clone this branch and [install from
source](https://docs.gitea.io/en-us/install-from-source).

Add additional configurations in `app.ini` to enable Actions:

```ini
[actions]
ENABLED = true
```

Start it.

If all is well, you'll see the management page of runners:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205877365-8e30a780-9b10-4154-b3e8-ee6c3cb35a59.png">


#### 2. Start runner

Clone the [act_runner](https://gitea.com/gitea/act_runner), and follow
the
[README](https://gitea.com/gitea/act_runner/src/branch/main/README.md)
to start it.

If all is well, you'll see a new runner has been added:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205878000-216f5937-e696-470d-b66c-8473987d91c3.png">

#### 3. Enable actions for a repo

Create a new repo or open an existing one, check the `Actions` checkbox
in settings and submit.

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205879705-53e09208-73c0-4b3e-a123-2dcf9aba4b9c.png">
<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205879383-23f3d08f-1a85-41dd-a8b3-54e2ee6453e8.png">

If all is well, you'll see a new tab "Actions":

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205881648-a8072d8c-5803-4d76-b8a8-9b2fb49516c1.png">

#### 4. Upload workflow files

Upload some workflow files to `.gitea/workflows/xxx.yaml`, you can
follow the [quickstart](https://docs.github.com/en/actions/quickstart)
of GitHub Actions. Yes, Gitea Actions is compatible with GitHub Actions
in most cases, you can use the same demo:

```yaml
name: GitHub Actions Demo
run-name: ${{ github.actor }} is testing out GitHub Actions 🚀
on: [push]
jobs:
  Explore-GitHub-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event."
      - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!"
      - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
      - name: Check out repository code
        uses: actions/checkout@v3
      - run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner."
      - run: echo "🖥️ The workflow is now ready to test your code on the runner."
      - name: List files in the repository
        run: |
          ls ${{ github.workspace }}
      - run: echo "🍏 This job's status is ${{ job.status }}."
```

If all is well, you'll see a new run in `Actions` tab:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205884473-79a874bc-171b-4aaf-acd5-0241a45c3b53.png">

#### 5. Check the logs of jobs

Click a run and you'll see the logs:

<img width="1792" alt="image"
src="https://user-images.githubusercontent.com/9418365/205884800-994b0374-67f7-48ff-be9a-4c53f3141547.png">

#### 6. Go on

You can try more examples in [the
documents](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)
of GitHub Actions, then you might find a lot of bugs.

Come on, PRs are welcome.

</details>

See also: [Feature Preview: Gitea
Actions](https://blog.gitea.io/2022/12/feature-preview-gitea-actions/)

---------

Co-authored-by: a1012112796 <1012112796@qq.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: ChristopherHX <christopher.homberger@web.de>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2023-01-31 09:45:19 +08:00
Sybren 326d29dce0
Reliable selection of admin user (#22509)
When importing a repository via `gitea restore-repo`, external users
will get remapped to an admin user. This admin user is obtained via
`users.GetAdminUser()`, which unfortunately picks a more-or-less random
admin to return.

This makes it hard to predict which admin user will get assigned. This
patch orders the admin by ascending ID before choosing the first one,
i.e. it picks the admin with the lowest ID.

Even though it would be nicer to have full control over which user is
chosen, this at least gives us a predictable result.
2023-01-18 10:57:16 -06:00
Xinyu Zhou 7cc7db73b9
Add option to prohibit fork if user reached maximum limit of repositories (#21848)
If user has reached the maximum limit of repositories:

- Before
  - disallow create
  - allow fork without limit
- This patch:
  - disallow create
  - disallow fork
- Add option `ALLOW_FORK_WITHOUT_MAXIMUM_LIMIT` (Default **true**) :
enable this allow user fork repositories without maximum number limit

fixed https://github.com/go-gitea/gitea/issues/21847

Signed-off-by: Xinyu Zhou <i@sourcehut.net>
2022-12-27 15:21:14 -06:00
Lunny Xiao 0a7d3ff786
refactor some functions to support ctx as first parameter (#21878)
Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: Lauris BH <lauris@nix.lv>
2022-12-03 10:48:26 +08:00
Jason Song 9607750b5e
Replace fmt.Sprintf with hex.EncodeToString (#21960)
`hex.EncodeToString` has better performance than `fmt.Sprintf("%x",
[]byte)`, we should use it as much as possible.

I'm not an extreme fan of performance, so I think there are some
exceptions:

- `fmt.Sprintf("%x", func(...)[N]byte())`
- We can't slice the function return value directly, and it's not worth
adding lines.
    ```diff
    func A()[20]byte { ... }
    - a := fmt.Sprintf("%x", A())
    - a := hex.EncodeToString(A()[:]) // invalid
    + tmp := A()
    + a := hex.EncodeToString(tmp[:])
    ```
- `fmt.Sprintf("%X", []byte)`
- `strings.ToUpper(hex.EncodeToString(bytes))` has even worse
performance.
2022-11-28 11:19:18 +00:00
flynnnnnnnnnn e81ccc406b
Implement FSFE REUSE for golang files (#21840)
Change all license headers to comply with REUSE specification.

Fix #16132

Co-authored-by: flynnnnnnnnnn <flynnnnnnnnnn@github>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2022-11-27 18:20:29 +00:00
KN4CK3R 044c754ea5
Add context.Context to more methods (#21546)
This PR adds a context parameter to a bunch of methods. Some helper
`xxxCtx()` methods got replaced with the normal name now.

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2022-11-19 16:12:33 +08:00
Lunny Xiao 34283a74e8
Allow detect whether it's in a database transaction for a context.Context (#21756)
Fix #19513

This PR introduce a new db method `InTransaction(context.Context)`,
and also builtin check on `db.TxContext` and `db.WithTx`.
There is also a new method `db.AutoTx` has been introduced but could be used by other PRs.

`WithTx` will always open a new transaction, if a transaction exist in context, return an error.
`AutoTx` will try to open a new transaction if no transaction exist in context.
That means it will always enter a transaction if there is no error.

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: 6543 <6543@obermui.de>
2022-11-12 21:18:50 +01:00
wxiaoguang 2900dc90a7
Improve valid user name check (#20136)
Close https://github.com/go-gitea/gitea/issues/21640

Before: Gitea can create users like ".xxx" or "x..y", which is not
ideal, it's already a consensus that dot filenames have special
meanings, and `a..b` is a confusing name when doing cross repo compare.

After: stricter

Co-authored-by: Jason Song <i@wolfogre.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: delvh <dev.lh@web.de>
2022-11-04 17:04:08 +08:00
delvh 0ebb45cfe7
Replace all instances of fmt.Errorf(%v) with fmt.Errorf(%w) (#21551)
Found using
`find . -type f -name '*.go' -print -exec vim {} -c
':%s/fmt\.Errorf(\(.*\)%v\(.*\)err/fmt.Errorf(\1%w\2err/g' -c ':wq' \;`

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2022-10-24 20:29:17 +01:00