1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo.git synced 2024-11-29 09:31:11 -05:00
forgejo/routers/web/auth/auth.go

884 lines
26 KiB
Go
Raw Normal View History

2022-01-02 08:12:35 -05:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Copyright 2018 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2022-01-02 08:12:35 -05:00
package auth
import (
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
"crypto/subtle"
"encoding/hex"
"errors"
2022-01-02 08:12:35 -05:00
"fmt"
"net/http"
"strings"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/auth/password"
2022-01-02 08:12:35 -05:00
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/eventsource"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/optional"
2022-01-02 08:12:35 -05:00
"code.gitea.io/gitea/modules/session"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/timeutil"
"code.gitea.io/gitea/modules/util"
2022-01-02 08:12:35 -05:00
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/modules/web/middleware"
"code.gitea.io/gitea/routers/utils"
auth_service "code.gitea.io/gitea/services/auth"
"code.gitea.io/gitea/services/auth/source/oauth2"
"code.gitea.io/gitea/services/context"
2022-01-02 08:12:35 -05:00
"code.gitea.io/gitea/services/externalaccount"
"code.gitea.io/gitea/services/forms"
"code.gitea.io/gitea/services/mailer"
[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 c721aa828ba6aec5ef95459cfc632a0a1f7463e9) (cherry picked from commit 6487efcb9da61be1f802f1cd8007330153322770) 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 7ea66ee1c5dd21d9e6a43f961e8adc71ec79b806) Conflicts: services/notify/notifier.go services/notify/notify.go services/notify/null.go https://codeberg.org/forgejo/forgejo/pulls/1469 (cherry picked from commit 7d2d9970115c94954dacb45684f9e3c16117ebfe) (cherry picked from commit 435a54f14039408b315c99063bdce28c7ef6fe2f) (cherry picked from commit 8ec7b3e4484383445fa2622a28bb4f5c990dd4f2) [GITEA] notifies admins on new user registration (squash) performance bottleneck Refs: https://codeberg.org/forgejo/forgejo/issues/1479 (cherry picked from commit 97ac9147ff3643cca0a059688c6b3c53479e28a7) (cherry picked from commit 19f295c16bd392aa438477fa3c42038d63d1a06a) (cherry picked from commit 3367dcb2cf5328e2afc89f7d5a008b64ede1c987) [GITEA] notifies admins on new user registration (squash) cosmetic changes Co-authored-by: delvh <dev.lh@web.de> (cherry picked from commit 9f1670e040b469ed4346aa2689a75088e4e71c8b) (cherry picked from commit de5bb2a224ab2ae9be891de1ee88a7454a07f7e9) (cherry picked from commit 8f8e52f31a4da080465521747a2c5c0c51ed65e3) (cherry picked from commit e0d51303129fe8763d87ed5f859eeae8f0cc6188) (cherry picked from commit f1288d6d9bfc9150596cb2f7ddb7300cf7ab6952) (cherry picked from commit 1db4736fd7cd75027f3cdf805e0f86c3a5f69c9d) (cherry picked from commit e8dcbb6cd68064209cdbe054d5886710cbe2925d) (cherry picked from commit 09625d647629b85397270e14dfe22258df2bcc43) [GITEA] notifies admins on new user registration (squash) ctx.Locale (cherry picked from commit dab7212fad44a252a1acf8da71b254b1a6715121) (cherry picked from commit 9b7bbae8c4cd5dc4d36726f10870462c8985e543) (cherry picked from commit f750b71d3db9a24dc2722effb8bbc2dded657cbb) (cherry picked from commit f79af366796a8ab581bbfa1f5609dc721798ae68) (cherry picked from commit e76eee334e446a45d841caf19a7c18eab89ca457) [GITEA] notifies admins on new user registration (squash) fix locale (cherry picked from commit 54cd100d8da37ccb0a545e2545995066f92180f0) (cherry picked from commit 053dbd3d50d3c7d1afae8d31c25bda92ceb8f8c0) [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 b8d764e36a0cd8e60627805f87b84bb04152e9c1) (cherry picked from commit d48b84f623e369222e5e15965f22e27d74ff4243) Conflicts: routers/web/auth/auth.go https://codeberg.org/forgejo/forgejo/pulls/2034 (cherry picked from commit 02d3c125ccc97638849af33c7df315cbcb368127) (cherry picked from commit 367374ecc3832bb47d29ff79370103f907d0ca99) Conflicts: models/user/user_test.go https://codeberg.org/forgejo/forgejo/pulls/2119 (cherry picked from commit 4124fa5aa41c36b3ab3cc1c65d0e3d5e05ec4086) (cherry picked from commit 7f12610ff63d4907631d8cddcd7a49ae6f6e1508) [GITEA] notifies admins on new user registration (squash) DeleteByID trivial conflict because of 778ad795fd4a19dc15723b59a846a250034c7c3a Refactor deletion (#28610) (cherry picked from commit 05682614e5ef2462cbb6a1635ca01e296fe03d23) (cherry picked from commit 64bd374803a76c97619fe1e28bfc74f99ec91677) (cherry picked from commit 63d086f666a880b48d034b129e535fcfc82acf7d) (cherry picked from commit 3cd48ef4d53c55a81c97f1b666b8d4ba16a967c4) Conflicts: options/locale/locale_en-US.ini https://codeberg.org/forgejo/forgejo/pulls/2249 (cherry picked from commit 6578ec4ed64c8624bc202cefb18d67870eec1336) Conflicts: routers/web/auth/auth.go https://codeberg.org/forgejo/forgejo/pulls/2300
2023-09-07 03:11:29 -04:00
notify_service "code.gitea.io/gitea/services/notify"
user_service "code.gitea.io/gitea/services/user"
2022-01-02 08:12:35 -05:00
"github.com/markbates/goth"
)
const (
// tplSignIn template for sign in page
tplSignIn base.TplName = "user/auth/signin"
// tplSignUp template path for sign up page
tplSignUp base.TplName = "user/auth/signup"
// TplActivate template path for activate user
TplActivate base.TplName = "user/auth/activate"
)
// autoSignIn reads cookie and try to auto-login.
func autoSignIn(ctx *context.Context) (bool, error) {
2022-01-02 08:12:35 -05:00
isSucceed := false
defer func() {
if !isSucceed {
ctx.DeleteSiteCookie(setting.CookieRememberName)
2022-01-02 08:12:35 -05:00
}
}()
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
authCookie := ctx.GetSiteCookie(setting.CookieRememberName)
if len(authCookie) == 0 {
return false, nil
}
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
lookupKey, validator, found := strings.Cut(authCookie, ":")
if !found {
return false, nil
}
authToken, err := auth.FindAuthToken(ctx, lookupKey)
2022-01-02 08:12:35 -05:00
if err != nil {
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
if errors.Is(err, util.ErrNotExist) {
return false, nil
2022-01-02 08:12:35 -05:00
}
return false, err
}
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
if authToken.IsExpired() {
err = auth.DeleteAuthToken(ctx, authToken)
return false, err
}
rawValidator, err := hex.DecodeString(validator)
if err != nil {
return false, err
}
if subtle.ConstantTimeCompare([]byte(authToken.HashedValidator), []byte(auth.HashValidator(rawValidator))) == 0 {
2022-01-02 08:12:35 -05:00
return false, nil
}
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
u, err := user_model.GetUserByID(ctx, authToken.UID)
if err != nil {
if !user_model.IsErrUserNotExist(err) {
return false, fmt.Errorf("GetUserByID: %w", err)
}
2022-01-02 08:12:35 -05:00
return false, nil
}
isSucceed = true
if err := updateSession(ctx, nil, map[string]any{
// Set session IDs
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
"uid": u.ID,
}); err != nil {
return false, fmt.Errorf("unable to updateSession: %w", err)
2022-01-02 08:12:35 -05:00
}
if err := resetLocale(ctx, u); err != nil {
return false, err
}
ctx.Csrf.DeleteCookie(ctx)
2022-01-02 08:12:35 -05:00
return true, nil
}
func resetLocale(ctx *context.Context, u *user_model.User) error {
// Language setting of the user overwrites the one previously set
// If the user does not have a locale set, we save the current one.
if u.Language == "" {
opts := &user_service.UpdateOptions{
Language: optional.Some(ctx.Locale.Language()),
}
if err := user_service.UpdateUser(ctx, u, opts); err != nil {
2022-01-02 08:12:35 -05:00
return err
}
}
middleware.SetLocaleCookie(ctx.Resp, u.Language, 0)
if ctx.Locale.Language() != u.Language {
ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req)
}
return nil
}
func RedirectAfterLogin(ctx *context.Context) {
redirectTo := ctx.FormString("redirect_to")
if redirectTo == "" {
redirectTo = ctx.GetSiteCookie("redirect_to")
}
middleware.DeleteRedirectToCookie(ctx.Resp)
nextRedirectTo := setting.AppSubURL + string(setting.LandingPageURL)
if setting.LandingPageURL == setting.LandingPageLogin {
nextRedirectTo = setting.AppSubURL + "/" // do not cycle-redirect to the login page
}
ctx.RedirectToFirst(redirectTo, nextRedirectTo)
}
func CheckAutoLogin(ctx *context.Context) bool {
isSucceed, err := autoSignIn(ctx) // try to auto-login
2022-01-02 08:12:35 -05:00
if err != nil {
ctx.ServerError("autoSignIn", err)
2022-01-02 08:12:35 -05:00
return true
}
redirectTo := ctx.FormString("redirect_to")
if len(redirectTo) > 0 {
middleware.SetRedirectToCookie(ctx.Resp, redirectTo)
}
if isSucceed {
RedirectAfterLogin(ctx)
2022-01-02 08:12:35 -05:00
return true
}
return false
}
// SignIn render sign in page
func SignIn(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("sign_in")
if CheckAutoLogin(ctx) {
2022-01-02 08:12:35 -05:00
return
}
if ctx.IsSigned {
RedirectAfterLogin(ctx)
return
}
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
2022-01-02 08:12:35 -05:00
if err != nil {
ctx.ServerError("UserSignIn", err)
return
}
ctx.Data["OAuth2Providers"] = oauth2Providers
ctx.Data["Title"] = ctx.Tr("sign_in")
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
2022-01-02 08:12:35 -05:00
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
context.SetCaptchaData(ctx)
}
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, tplSignIn)
}
// SignInPost response for sign in request
func SignInPost(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("sign_in")
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
2022-01-02 08:12:35 -05:00
if err != nil {
ctx.ServerError("UserSignIn", err)
return
}
ctx.Data["OAuth2Providers"] = oauth2Providers
ctx.Data["Title"] = ctx.Tr("sign_in")
ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login"
ctx.Data["PageIsSignIn"] = true
ctx.Data["PageIsLogin"] = true
ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled(ctx)
2022-01-02 08:12:35 -05:00
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSignIn)
return
}
form := web.GetForm(ctx).(*forms.SignInForm)
if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin {
context.SetCaptchaData(ctx)
context.VerifyCaptcha(ctx, tplSignIn, form)
if ctx.Written() {
return
}
}
u, source, err := auth_service.UserSignIn(ctx, form.UserName, form.Password)
2022-01-02 08:12:35 -05:00
if err != nil {
if errors.Is(err, util.ErrNotExist) || errors.Is(err, util.ErrInvalidArgument) {
2022-01-02 08:12:35 -05:00
ctx.RenderWithErr(ctx.Tr("form.username_password_incorrect"), tplSignIn, &form)
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
} else if user_model.IsErrEmailAlreadyUsed(err) {
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplSignIn, &form)
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
} else if user_model.IsErrUserProhibitLogin(err) {
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
} else if user_model.IsErrUserInactive(err) {
if setting.Service.RegisterEmailConfirm {
ctx.Data["Title"] = ctx.Tr("auth.active_your_account")
ctx.HTML(http.StatusOK, TplActivate)
} else {
log.Info("Failed authentication attempt for %s from %s: %v", form.UserName, ctx.RemoteAddr(), err)
ctx.Data["Title"] = ctx.Tr("auth.prohibit_login")
ctx.HTML(http.StatusOK, "user/auth/prohibit_login")
}
} else {
ctx.ServerError("UserSignIn", err)
}
return
}
// Now handle 2FA:
// First of all if the source can skip local two fa we're done
if skipper, ok := source.Cfg.(auth_service.LocalTwoFASkipper); ok && skipper.IsSkipLocalTwoFA() {
handleSignIn(ctx, u, form.Remember)
return
}
// If this user is enrolled in 2FA TOTP, we can't sign the user in just yet.
// Instead, redirect them to the 2FA authentication page.
hasTOTPtwofa, err := auth.HasTwoFactorByUID(ctx, u.ID)
2022-01-02 08:12:35 -05:00
if err != nil {
ctx.ServerError("UserSignIn", err)
return
}
// Check if the user has webauthn registration
hasWebAuthnTwofa, err := auth.HasWebAuthnRegistrationsByUID(ctx, u.ID)
2022-01-02 08:12:35 -05:00
if err != nil {
ctx.ServerError("UserSignIn", err)
return
}
if !hasTOTPtwofa && !hasWebAuthnTwofa {
2022-01-02 08:12:35 -05:00
// No two factor auth configured we can sign in the user
handleSignIn(ctx, u, form.Remember)
return
}
updates := map[string]any{
// User will need to use 2FA TOTP or WebAuthn, save data
"twofaUid": u.ID,
"twofaRemember": form.Remember,
2022-01-02 08:12:35 -05:00
}
if hasTOTPtwofa {
// User will need to use WebAuthn, save data
updates["totpEnrolled"] = u.ID
2022-01-02 08:12:35 -05:00
}
if err := updateSession(ctx, nil, updates); err != nil {
ctx.ServerError("UserSignIn: Unable to update session", err)
2022-01-02 08:12:35 -05:00
return
}
// If we have WebAuthn redirect there first
if hasWebAuthnTwofa {
ctx.Redirect(setting.AppSubURL + "/user/webauthn")
2022-01-02 08:12:35 -05:00
return
}
// Fallback to 2FA
ctx.Redirect(setting.AppSubURL + "/user/two_factor")
}
// This handles the final part of the sign-in process of the user.
func handleSignIn(ctx *context.Context, u *user_model.User, remember bool) {
redirect := handleSignInFull(ctx, u, remember, true)
if ctx.Written() {
return
}
ctx.Redirect(redirect)
}
func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRedirect bool) string {
2022-01-02 08:12:35 -05:00
if remember {
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
if err := ctx.SetLTACookie(u); err != nil {
ctx.ServerError("GenerateAuthToken", err)
return setting.AppSubURL + "/"
}
2022-01-02 08:12:35 -05:00
}
if err := updateSession(ctx, []string{
// Delete the openid, 2fa and linkaccount data
"openid_verified_uri",
"openid_signin_remember",
"openid_determined_email",
"openid_determined_username",
"twofaUid",
"twofaRemember",
"linkAccount",
}, map[string]any{
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
"uid": u.ID,
}); err != nil {
2022-01-02 08:12:35 -05:00
ctx.ServerError("RegenerateSession", err)
return setting.AppSubURL + "/"
}
// Language setting of the user overwrites the one previously set
// If the user does not have a locale set, we save the current one.
if u.Language == "" {
opts := &user_service.UpdateOptions{
Language: optional.Some(ctx.Locale.Language()),
}
if err := user_service.UpdateUser(ctx, u, opts); err != nil {
ctx.ServerError("UpdateUser Language", fmt.Errorf("Error updating user language [user: %d, locale: %s]", u.ID, ctx.Locale.Language()))
2022-01-02 08:12:35 -05:00
return setting.AppSubURL + "/"
}
}
middleware.SetLocaleCookie(ctx.Resp, u.Language, 0)
if ctx.Locale.Language() != u.Language {
ctx.Locale = middleware.Locale(ctx.Resp, ctx.Req)
}
// Clear whatever CSRF cookie has right now, force to generate a new one
ctx.Csrf.DeleteCookie(ctx)
2022-01-02 08:12:35 -05:00
// Register last login
if err := user_service.UpdateUser(ctx, u, &user_service.UpdateOptions{SetLastLogin: true}); err != nil {
ctx.ServerError("UpdateUser", err)
2022-01-02 08:12:35 -05:00
return setting.AppSubURL + "/"
}
if redirectTo := ctx.GetSiteCookie("redirect_to"); len(redirectTo) > 0 && !utils.IsExternalURL(redirectTo) {
2022-01-02 08:12:35 -05:00
middleware.DeleteRedirectToCookie(ctx.Resp)
if obeyRedirect {
ctx.RedirectToFirst(redirectTo)
}
return redirectTo
}
if obeyRedirect {
ctx.Redirect(setting.AppSubURL + "/")
}
return setting.AppSubURL + "/"
}
func getUserName(gothUser *goth.User) (string, error) {
2022-01-02 08:12:35 -05:00
switch setting.OAuth2Client.Username {
case setting.OAuth2UsernameEmail:
return user_model.NormalizeUserName(strings.Split(gothUser.Email, "@")[0])
2022-01-02 08:12:35 -05:00
case setting.OAuth2UsernameNickname:
return user_model.NormalizeUserName(gothUser.NickName)
2022-01-02 08:12:35 -05:00
default: // OAuth2UsernameUserid
return gothUser.UserID, nil
2022-01-02 08:12:35 -05:00
}
}
// HandleSignOut resets the session and sets the cookies
func HandleSignOut(ctx *context.Context) {
_ = ctx.Session.Flush()
_ = ctx.Session.Destroy(ctx.Resp, ctx.Req)
ctx.DeleteSiteCookie(setting.CookieRememberName)
ctx.Csrf.DeleteCookie(ctx)
2022-01-02 08:12:35 -05:00
middleware.DeleteRedirectToCookie(ctx.Resp)
}
// SignOut sign out from login status
func SignOut(ctx *context.Context) {
if ctx.Doer != nil {
eventsource.GetManager().SendMessageBlocking(ctx.Doer.ID, &eventsource.Event{
2022-01-02 08:12:35 -05:00
Name: "logout",
Data: ctx.Session.ID(),
})
}
HandleSignOut(ctx)
ctx.JSONRedirect(setting.AppSubURL + "/")
2022-01-02 08:12:35 -05:00
}
// SignUp render the register page
func SignUp(ctx *context.Context) {
ctx.Data["Title"] = ctx.Tr("sign_up")
ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
if err != nil {
ctx.ServerError("UserSignUp", err)
return
}
ctx.Data["OAuth2Providers"] = oauth2Providers
context.SetCaptchaData(ctx)
2022-01-02 08:12:35 -05:00
ctx.Data["PageIsSignUp"] = true
// Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true
2022-01-02 08:12:35 -05:00
ctx.Data["DisableRegistration"] = setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration
redirectTo := ctx.FormString("redirect_to")
if len(redirectTo) > 0 {
middleware.SetRedirectToCookie(ctx.Resp, redirectTo)
}
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, tplSignUp)
}
// SignUpPost response for sign up information submission
func SignUpPost(ctx *context.Context) {
form := web.GetForm(ctx).(*forms.RegisterForm)
ctx.Data["Title"] = ctx.Tr("sign_up")
ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up"
oauth2Providers, err := oauth2.GetOAuth2Providers(ctx, optional.Some(true))
if err != nil {
ctx.ServerError("UserSignUp", err)
return
}
ctx.Data["OAuth2Providers"] = oauth2Providers
context.SetCaptchaData(ctx)
2022-01-02 08:12:35 -05:00
ctx.Data["PageIsSignUp"] = true
// Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true
2022-01-02 08:12:35 -05:00
if setting.Service.DisableRegistration || setting.Service.AllowOnlyExternalRegistration {
ctx.Error(http.StatusForbidden)
return
}
if ctx.HasError() {
ctx.HTML(http.StatusOK, tplSignUp)
return
}
context.VerifyCaptcha(ctx, tplSignUp, form)
if ctx.Written() {
return
2022-01-02 08:12:35 -05:00
}
if !form.IsEmailDomainAllowed() {
ctx.RenderWithErr(ctx.Tr("auth.email_domain_blacklisted"), tplSignUp, &form)
return
}
if form.Password != form.Retype {
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("form.password_not_match"), tplSignUp, &form)
return
}
if len(form.Password) < setting.MinPasswordLength {
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplSignUp, &form)
return
}
if !password.IsComplexEnough(form.Password) {
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(password.BuildComplexityError(ctx.Locale), tplSignUp, &form)
2022-01-02 08:12:35 -05:00
return
}
if err := password.IsPwned(ctx, form.Password); err != nil {
2022-01-02 08:12:35 -05:00
errMsg := ctx.Tr("auth.password_pwned")
if password.IsErrIsPwnedRequest(err) {
2022-01-02 08:12:35 -05:00
log.Error(err.Error())
errMsg = ctx.Tr("auth.password_pwned_err")
}
ctx.Data["Err_Password"] = true
ctx.RenderWithErr(errMsg, tplSignUp, &form)
return
}
u := &user_model.User{
Name: form.UserName,
Email: form.Email,
Passwd: form.Password,
2022-01-02 08:12:35 -05:00
}
if !createAndHandleCreatedUser(ctx, tplSignUp, form, u, nil, nil, false) {
2022-01-02 08:12:35 -05:00
// error already handled
return
}
ctx.Flash.Success(ctx.Tr("auth.sign_up_successful"))
handleSignIn(ctx, u, false)
}
// createAndHandleCreatedUser calls createUserInContext and
// then handleUserCreated.
func createAndHandleCreatedUser(ctx *context.Context, tpl base.TplName, form any, u *user_model.User, overwrites *user_model.CreateUserOverwriteOptions, gothUser *goth.User, allowLink bool) bool {
if !createUserInContext(ctx, tpl, form, u, overwrites, gothUser, allowLink) {
2022-01-02 08:12:35 -05:00
return false
}
return handleUserCreated(ctx, u, gothUser)
}
// createUserInContext creates a user and handles errors within a given context.
// Optionally a template can be specified.
func createUserInContext(ctx *context.Context, tpl base.TplName, form any, u *user_model.User, overwrites *user_model.CreateUserOverwriteOptions, gothUser *goth.User, allowLink bool) (ok bool) {
if err := user_model.CreateUser(ctx, u, overwrites); err != nil {
2022-01-02 08:12:35 -05:00
if allowLink && (user_model.IsErrUserAlreadyExist(err) || user_model.IsErrEmailAlreadyUsed(err)) {
if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingAuto {
var user *user_model.User
user = &user_model.User{Name: u.Name}
hasUser, err := user_model.GetUser(ctx, user)
2022-01-02 08:12:35 -05:00
if !hasUser || err != nil {
user = &user_model.User{Email: u.Email}
hasUser, err = user_model.GetUser(ctx, user)
2022-01-02 08:12:35 -05:00
if !hasUser || err != nil {
ctx.ServerError("UserLinkAccount", err)
return false
2022-01-02 08:12:35 -05:00
}
}
// TODO: probably we should respect 'remember' user's choice...
linkAccount(ctx, user, *gothUser, true)
return false // user is already created here, all redirects are handled
2022-01-02 08:12:35 -05:00
} else if setting.OAuth2Client.AccountLinking == setting.OAuth2AccountLinkingLogin {
showLinkingLogin(ctx, *gothUser)
return false // user will be created only after linking login
2022-01-02 08:12:35 -05:00
}
}
// handle error without template
if len(tpl) == 0 {
ctx.ServerError("CreateUser", err)
return false
2022-01-02 08:12:35 -05:00
}
// handle error with template
switch {
case user_model.IsErrUserAlreadyExist(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tpl, form)
case user_model.IsErrEmailAlreadyUsed(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tpl, form)
case user_model.IsErrEmailCharIsNotSupported(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_invalid"), tpl, form)
2022-01-02 08:12:35 -05:00
case user_model.IsErrEmailInvalid(err):
ctx.Data["Err_Email"] = true
ctx.RenderWithErr(ctx.Tr("form.email_invalid"), tpl, form)
case db.IsErrNameReserved(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(db.ErrNameReserved).Name), tpl, form)
case db.IsErrNamePatternNotAllowed(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(db.ErrNamePatternNotAllowed).Pattern), tpl, form)
case db.IsErrNameCharsNotAllowed(err):
ctx.Data["Err_UserName"] = true
ctx.RenderWithErr(ctx.Tr("user.form.name_chars_not_allowed", err.(db.ErrNameCharsNotAllowed).Name), tpl, form)
default:
ctx.ServerError("CreateUser", err)
}
return false
2022-01-02 08:12:35 -05:00
}
log.Trace("Account created: %s", u.Name)
return true
}
// handleUserCreated does additional steps after a new user is created.
// It auto-sets admin for the only user, updates the optional external user and
// sends a confirmation email if required.
func handleUserCreated(ctx *context.Context, u *user_model.User, gothUser *goth.User) (ok bool) {
// Auto-set admin for the only user.
if user_model.CountUsers(ctx, nil) == 1 {
opts := &user_service.UpdateOptions{
IsActive: optional.Some(true),
IsAdmin: optional.Some(true),
SetLastLogin: true,
}
if err := user_service.UpdateUser(ctx, u, opts); err != nil {
2022-01-02 08:12:35 -05:00
ctx.ServerError("UpdateUser", err)
return false
2022-01-02 08:12:35 -05:00
}
}
[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 c721aa828ba6aec5ef95459cfc632a0a1f7463e9) (cherry picked from commit 6487efcb9da61be1f802f1cd8007330153322770) 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 7ea66ee1c5dd21d9e6a43f961e8adc71ec79b806) Conflicts: services/notify/notifier.go services/notify/notify.go services/notify/null.go https://codeberg.org/forgejo/forgejo/pulls/1469 (cherry picked from commit 7d2d9970115c94954dacb45684f9e3c16117ebfe) (cherry picked from commit 435a54f14039408b315c99063bdce28c7ef6fe2f) (cherry picked from commit 8ec7b3e4484383445fa2622a28bb4f5c990dd4f2) [GITEA] notifies admins on new user registration (squash) performance bottleneck Refs: https://codeberg.org/forgejo/forgejo/issues/1479 (cherry picked from commit 97ac9147ff3643cca0a059688c6b3c53479e28a7) (cherry picked from commit 19f295c16bd392aa438477fa3c42038d63d1a06a) (cherry picked from commit 3367dcb2cf5328e2afc89f7d5a008b64ede1c987) [GITEA] notifies admins on new user registration (squash) cosmetic changes Co-authored-by: delvh <dev.lh@web.de> (cherry picked from commit 9f1670e040b469ed4346aa2689a75088e4e71c8b) (cherry picked from commit de5bb2a224ab2ae9be891de1ee88a7454a07f7e9) (cherry picked from commit 8f8e52f31a4da080465521747a2c5c0c51ed65e3) (cherry picked from commit e0d51303129fe8763d87ed5f859eeae8f0cc6188) (cherry picked from commit f1288d6d9bfc9150596cb2f7ddb7300cf7ab6952) (cherry picked from commit 1db4736fd7cd75027f3cdf805e0f86c3a5f69c9d) (cherry picked from commit e8dcbb6cd68064209cdbe054d5886710cbe2925d) (cherry picked from commit 09625d647629b85397270e14dfe22258df2bcc43) [GITEA] notifies admins on new user registration (squash) ctx.Locale (cherry picked from commit dab7212fad44a252a1acf8da71b254b1a6715121) (cherry picked from commit 9b7bbae8c4cd5dc4d36726f10870462c8985e543) (cherry picked from commit f750b71d3db9a24dc2722effb8bbc2dded657cbb) (cherry picked from commit f79af366796a8ab581bbfa1f5609dc721798ae68) (cherry picked from commit e76eee334e446a45d841caf19a7c18eab89ca457) [GITEA] notifies admins on new user registration (squash) fix locale (cherry picked from commit 54cd100d8da37ccb0a545e2545995066f92180f0) (cherry picked from commit 053dbd3d50d3c7d1afae8d31c25bda92ceb8f8c0) [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 b8d764e36a0cd8e60627805f87b84bb04152e9c1) (cherry picked from commit d48b84f623e369222e5e15965f22e27d74ff4243) Conflicts: routers/web/auth/auth.go https://codeberg.org/forgejo/forgejo/pulls/2034 (cherry picked from commit 02d3c125ccc97638849af33c7df315cbcb368127) (cherry picked from commit 367374ecc3832bb47d29ff79370103f907d0ca99) Conflicts: models/user/user_test.go https://codeberg.org/forgejo/forgejo/pulls/2119 (cherry picked from commit 4124fa5aa41c36b3ab3cc1c65d0e3d5e05ec4086) (cherry picked from commit 7f12610ff63d4907631d8cddcd7a49ae6f6e1508) [GITEA] notifies admins on new user registration (squash) DeleteByID trivial conflict because of 778ad795fd4a19dc15723b59a846a250034c7c3a Refactor deletion (#28610) (cherry picked from commit 05682614e5ef2462cbb6a1635ca01e296fe03d23) (cherry picked from commit 64bd374803a76c97619fe1e28bfc74f99ec91677) (cherry picked from commit 63d086f666a880b48d034b129e535fcfc82acf7d) (cherry picked from commit 3cd48ef4d53c55a81c97f1b666b8d4ba16a967c4) Conflicts: options/locale/locale_en-US.ini https://codeberg.org/forgejo/forgejo/pulls/2249 (cherry picked from commit 6578ec4ed64c8624bc202cefb18d67870eec1336) Conflicts: routers/web/auth/auth.go https://codeberg.org/forgejo/forgejo/pulls/2300
2023-09-07 03:11:29 -04:00
notify_service.NewUserSignUp(ctx, u)
2022-01-02 08:12:35 -05:00
// update external user information
if gothUser != nil {
if err := externalaccount.UpdateExternalUser(ctx, u, *gothUser); err != nil {
if !errors.Is(err, util.ErrNotExist) {
log.Error("UpdateExternalUser failed: %v", err)
}
2022-01-02 08:12:35 -05:00
}
}
// Send confirmation email
if !u.IsActive && u.ID > 1 {
if setting.Service.RegisterManualConfirm {
ctx.Data["ManualActivationOnly"] = true
ctx.HTML(http.StatusOK, TplActivate)
return false
}
2022-01-02 08:12:35 -05:00
mailer.SendActivateAccountMail(ctx.Locale, u)
ctx.Data["IsSendRegisterMail"] = true
ctx.Data["Email"] = u.Email
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale)
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, TplActivate)
if err := ctx.Cache.Put("MailResendLimit_"+u.LowerName, u.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
2022-01-02 08:12:35 -05:00
}
return false
2022-01-02 08:12:35 -05:00
}
return true
}
// Activate render activate user page
func Activate(ctx *context.Context) {
code := ctx.FormString("code")
if len(code) == 0 {
ctx.Data["IsActivatePage"] = true
if ctx.Doer == nil || ctx.Doer.IsActive {
2022-01-02 08:12:35 -05:00
ctx.NotFound("invalid user", nil)
return
}
// Resend confirmation email.
if setting.Service.RegisterEmailConfirm {
[GITEA] Allow changing the email address before activation During registration, one may be required to give their email address, to be verified and activated later. However, if one makes a mistake, a typo, they may end up with an account that cannot be activated due to having a wrong email address. They can still log in, but not change the email address, thus, no way to activate it without help from an administrator. To remedy this issue, lets allow changing the email address for logged in, but not activated users. This fixes gitea#17785. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit aaaece28e4c6a8980cef932e224e84933d7c9262) (cherry picked from commit 639dafabec0a5c1f943b44ca02f72c5ba2fc5e10) (cherry picked from commit d699c12cebea7dbbda950ae257a46d53c39f22ea) [GITEA] Allow changing the email address before activation (squash) cache is always active This needs to be revisited because the MailResendLimit is not enforced and turns out to not be tested. See e7cb8da2a8 * Always enable caches (#28527) (cherry picked from commit 43ded8ee30ab5c7a40a456600cdaa8a0fbdccec2) Rate limit pre-activation email change separately Changing the email address before any email address is activated should be subject to a different rate limit than the normal activation email resending. If there's only one rate limit for both, then if a newly signed up quickly discovers they gave a wrong email address, they'd have to wait three minutes to change it. With the two separate limits, they don't - but they'll have to wait three minutes before they can change the email address again. The downside of this setup is that a malicious actor can alternate between resending and changing the email address (to something like `user+$idx@domain`, delivered to the same inbox) to effectively halving the rate limit. I do not think there's a better solution, and this feels like such a small attack surface that I'd deem it acceptable. The way the code works after this change is that `ActivatePost` will now check the `MailChangeLimit_user` key rather than `MailResendLimit_user`, and if we're within the limit, it will set `MailChangedJustNow_user`. The `Activate` method - which sends the activation email, whether it is a normal resend, or one following an email change - will check `MailChangedJustNow_user`, and if it is set, it will check the rate limit against `MailChangedLimit_user`, otherwise against `MailResendLimit_user`, and then will delete the `MailChangedJustNow_user` key from the cache. Fixes #2040. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit e35d2af2e56f4ecb3a4f6d1109d02c8aa1a6d182) (cherry picked from commit 03989418a70d3445e0edada7fbe5a4151d7836b1) (cherry picked from commit f50e0dfe5e90d6a31c5b59e687580e8b2725c22b) (cherry picked from commit cad9184a3653e6c80de2e006a0d699b816980987) (cherry picked from commit e2da5d7fe13a685606913a131687a94f9f5fcfeb) (cherry picked from commit 3a80534d4db523efe56b368489f81dc1cb2c99f7)
2023-12-07 06:57:16 -05:00
var cacheKey string
if ctx.Cache.IsExist("MailChangedJustNow_" + ctx.Doer.LowerName) {
cacheKey = "MailChangedLimit_"
if err := ctx.Cache.Delete("MailChangedJustNow_" + ctx.Doer.LowerName); err != nil {
log.Error("Delete cache(MailChangedJustNow) fail: %v", err)
}
} else {
cacheKey = "MailResendLimit_"
}
if ctx.Cache.IsExist(cacheKey + ctx.Doer.LowerName) {
2022-01-02 08:12:35 -05:00
ctx.Data["ResendLimited"] = true
} else {
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale)
mailer.SendActivateAccountMail(ctx.Locale, ctx.Doer)
2022-01-02 08:12:35 -05:00
[GITEA] Allow changing the email address before activation During registration, one may be required to give their email address, to be verified and activated later. However, if one makes a mistake, a typo, they may end up with an account that cannot be activated due to having a wrong email address. They can still log in, but not change the email address, thus, no way to activate it without help from an administrator. To remedy this issue, lets allow changing the email address for logged in, but not activated users. This fixes gitea#17785. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit aaaece28e4c6a8980cef932e224e84933d7c9262) (cherry picked from commit 639dafabec0a5c1f943b44ca02f72c5ba2fc5e10) (cherry picked from commit d699c12cebea7dbbda950ae257a46d53c39f22ea) [GITEA] Allow changing the email address before activation (squash) cache is always active This needs to be revisited because the MailResendLimit is not enforced and turns out to not be tested. See e7cb8da2a8 * Always enable caches (#28527) (cherry picked from commit 43ded8ee30ab5c7a40a456600cdaa8a0fbdccec2) Rate limit pre-activation email change separately Changing the email address before any email address is activated should be subject to a different rate limit than the normal activation email resending. If there's only one rate limit for both, then if a newly signed up quickly discovers they gave a wrong email address, they'd have to wait three minutes to change it. With the two separate limits, they don't - but they'll have to wait three minutes before they can change the email address again. The downside of this setup is that a malicious actor can alternate between resending and changing the email address (to something like `user+$idx@domain`, delivered to the same inbox) to effectively halving the rate limit. I do not think there's a better solution, and this feels like such a small attack surface that I'd deem it acceptable. The way the code works after this change is that `ActivatePost` will now check the `MailChangeLimit_user` key rather than `MailResendLimit_user`, and if we're within the limit, it will set `MailChangedJustNow_user`. The `Activate` method - which sends the activation email, whether it is a normal resend, or one following an email change - will check `MailChangedJustNow_user`, and if it is set, it will check the rate limit against `MailChangedLimit_user`, otherwise against `MailResendLimit_user`, and then will delete the `MailChangedJustNow_user` key from the cache. Fixes #2040. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit e35d2af2e56f4ecb3a4f6d1109d02c8aa1a6d182) (cherry picked from commit 03989418a70d3445e0edada7fbe5a4151d7836b1) (cherry picked from commit f50e0dfe5e90d6a31c5b59e687580e8b2725c22b) (cherry picked from commit cad9184a3653e6c80de2e006a0d699b816980987) (cherry picked from commit e2da5d7fe13a685606913a131687a94f9f5fcfeb) (cherry picked from commit 3a80534d4db523efe56b368489f81dc1cb2c99f7)
2023-12-07 06:57:16 -05:00
if err := ctx.Cache.Put(cacheKey+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailResendLimit) fail: %v", err)
2022-01-02 08:12:35 -05:00
}
}
} else {
ctx.Data["ServiceNotEnabled"] = true
}
ctx.HTML(http.StatusOK, TplActivate)
return
}
user := user_model.VerifyUserActiveCode(ctx, code)
2022-01-02 08:12:35 -05:00
// if code is wrong
if user == nil {
ctx.Data["IsCodeInvalid"] = true
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, TplActivate)
return
}
// if account is local account, verify password
if user.LoginSource == 0 {
ctx.Data["Code"] = code
ctx.Data["NeedsPassword"] = true
ctx.HTML(http.StatusOK, TplActivate)
return
}
handleAccountActivation(ctx, user)
}
// ActivatePost handles account activation with password check
func ActivatePost(ctx *context.Context) {
code := ctx.FormString("code")
if len(code) == 0 {
[GITEA] Allow changing the email address before activation During registration, one may be required to give their email address, to be verified and activated later. However, if one makes a mistake, a typo, they may end up with an account that cannot be activated due to having a wrong email address. They can still log in, but not change the email address, thus, no way to activate it without help from an administrator. To remedy this issue, lets allow changing the email address for logged in, but not activated users. This fixes gitea#17785. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit aaaece28e4c6a8980cef932e224e84933d7c9262) (cherry picked from commit 639dafabec0a5c1f943b44ca02f72c5ba2fc5e10) (cherry picked from commit d699c12cebea7dbbda950ae257a46d53c39f22ea) [GITEA] Allow changing the email address before activation (squash) cache is always active This needs to be revisited because the MailResendLimit is not enforced and turns out to not be tested. See e7cb8da2a8 * Always enable caches (#28527) (cherry picked from commit 43ded8ee30ab5c7a40a456600cdaa8a0fbdccec2) Rate limit pre-activation email change separately Changing the email address before any email address is activated should be subject to a different rate limit than the normal activation email resending. If there's only one rate limit for both, then if a newly signed up quickly discovers they gave a wrong email address, they'd have to wait three minutes to change it. With the two separate limits, they don't - but they'll have to wait three minutes before they can change the email address again. The downside of this setup is that a malicious actor can alternate between resending and changing the email address (to something like `user+$idx@domain`, delivered to the same inbox) to effectively halving the rate limit. I do not think there's a better solution, and this feels like such a small attack surface that I'd deem it acceptable. The way the code works after this change is that `ActivatePost` will now check the `MailChangeLimit_user` key rather than `MailResendLimit_user`, and if we're within the limit, it will set `MailChangedJustNow_user`. The `Activate` method - which sends the activation email, whether it is a normal resend, or one following an email change - will check `MailChangedJustNow_user`, and if it is set, it will check the rate limit against `MailChangedLimit_user`, otherwise against `MailResendLimit_user`, and then will delete the `MailChangedJustNow_user` key from the cache. Fixes #2040. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit e35d2af2e56f4ecb3a4f6d1109d02c8aa1a6d182) (cherry picked from commit 03989418a70d3445e0edada7fbe5a4151d7836b1) (cherry picked from commit f50e0dfe5e90d6a31c5b59e687580e8b2725c22b) (cherry picked from commit cad9184a3653e6c80de2e006a0d699b816980987) (cherry picked from commit e2da5d7fe13a685606913a131687a94f9f5fcfeb) (cherry picked from commit 3a80534d4db523efe56b368489f81dc1cb2c99f7)
2023-12-07 06:57:16 -05:00
email := ctx.FormString("email")
if len(email) > 0 {
ctx.Data["IsActivatePage"] = true
if ctx.Doer == nil || ctx.Doer.IsActive {
ctx.NotFound("invalid user", nil)
return
}
// Change the primary email
if setting.Service.RegisterEmailConfirm {
if ctx.Cache.IsExist("MailChangeLimit_" + ctx.Doer.LowerName) {
ctx.Data["ResendLimited"] = true
} else {
ctx.Data["ActiveCodeLives"] = timeutil.MinutesToFriendly(setting.Service.ActiveCodeLives, ctx.Locale)
err := user_service.ReplaceInactivePrimaryEmail(ctx, ctx.Doer.Email, &user_model.EmailAddress{
[GITEA] Allow changing the email address before activation During registration, one may be required to give their email address, to be verified and activated later. However, if one makes a mistake, a typo, they may end up with an account that cannot be activated due to having a wrong email address. They can still log in, but not change the email address, thus, no way to activate it without help from an administrator. To remedy this issue, lets allow changing the email address for logged in, but not activated users. This fixes gitea#17785. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit aaaece28e4c6a8980cef932e224e84933d7c9262) (cherry picked from commit 639dafabec0a5c1f943b44ca02f72c5ba2fc5e10) (cherry picked from commit d699c12cebea7dbbda950ae257a46d53c39f22ea) [GITEA] Allow changing the email address before activation (squash) cache is always active This needs to be revisited because the MailResendLimit is not enforced and turns out to not be tested. See e7cb8da2a8 * Always enable caches (#28527) (cherry picked from commit 43ded8ee30ab5c7a40a456600cdaa8a0fbdccec2) Rate limit pre-activation email change separately Changing the email address before any email address is activated should be subject to a different rate limit than the normal activation email resending. If there's only one rate limit for both, then if a newly signed up quickly discovers they gave a wrong email address, they'd have to wait three minutes to change it. With the two separate limits, they don't - but they'll have to wait three minutes before they can change the email address again. The downside of this setup is that a malicious actor can alternate between resending and changing the email address (to something like `user+$idx@domain`, delivered to the same inbox) to effectively halving the rate limit. I do not think there's a better solution, and this feels like such a small attack surface that I'd deem it acceptable. The way the code works after this change is that `ActivatePost` will now check the `MailChangeLimit_user` key rather than `MailResendLimit_user`, and if we're within the limit, it will set `MailChangedJustNow_user`. The `Activate` method - which sends the activation email, whether it is a normal resend, or one following an email change - will check `MailChangedJustNow_user`, and if it is set, it will check the rate limit against `MailChangedLimit_user`, otherwise against `MailResendLimit_user`, and then will delete the `MailChangedJustNow_user` key from the cache. Fixes #2040. Signed-off-by: Gergely Nagy <forgejo@gergo.csillger.hu> (cherry picked from commit e35d2af2e56f4ecb3a4f6d1109d02c8aa1a6d182) (cherry picked from commit 03989418a70d3445e0edada7fbe5a4151d7836b1) (cherry picked from commit f50e0dfe5e90d6a31c5b59e687580e8b2725c22b) (cherry picked from commit cad9184a3653e6c80de2e006a0d699b816980987) (cherry picked from commit e2da5d7fe13a685606913a131687a94f9f5fcfeb) (cherry picked from commit 3a80534d4db523efe56b368489f81dc1cb2c99f7)
2023-12-07 06:57:16 -05:00
UID: ctx.Doer.ID,
Email: email,
})
if err != nil {
ctx.Data["IsActivatePage"] = false
log.Error("Couldn't replace inactive primary email of user %d: %v", ctx.Doer.ID, err)
ctx.RenderWithErr(ctx.Tr("auth.change_unconfirmed_email_error", err), TplActivate, nil)
return
}
if err := ctx.Cache.Put("MailChangeLimit_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailChangeLimit) fail: %v", err)
}
if err := ctx.Cache.Put("MailChangedJustNow_"+ctx.Doer.LowerName, ctx.Doer.LowerName, 180); err != nil {
log.Error("Set cache(MailChangedJustNow) fail: %v", err)
}
// Confirmation mail will be re-sent after the redirect to `/user/activate` below.
}
} else {
ctx.Data["ServiceNotEnabled"] = true
}
}
2022-01-02 08:12:35 -05:00
ctx.Redirect(setting.AppSubURL + "/user/activate")
return
}
user := user_model.VerifyUserActiveCode(ctx, code)
2022-01-02 08:12:35 -05:00
// if code is wrong
if user == nil {
ctx.Data["IsCodeInvalid"] = true
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, TplActivate)
return
}
// if account is local account, verify password
if user.LoginSource == 0 {
password := ctx.FormString("password")
if len(password) == 0 {
ctx.Data["Code"] = code
ctx.Data["NeedsPassword"] = true
ctx.HTML(http.StatusOK, TplActivate)
return
}
if !user.ValidatePassword(password) {
ctx.Data["IsPasswordInvalid"] = true
2022-01-02 08:12:35 -05:00
ctx.HTML(http.StatusOK, TplActivate)
return
}
}
handleAccountActivation(ctx, user)
}
func handleAccountActivation(ctx *context.Context, user *user_model.User) {
user.IsActive = true
var err error
if user.Rands, err = user_model.GetUserSalt(); err != nil {
ctx.ServerError("UpdateUser", err)
return
}
if err := user_model.UpdateUserCols(ctx, user, "is_active", "rands"); err != nil {
2022-01-02 08:12:35 -05:00
if user_model.IsErrUserNotExist(err) {
ctx.NotFound("UpdateUserCols", err)
} else {
ctx.ServerError("UpdateUser", err)
}
return
}
if err := user_model.ActivateUserEmail(ctx, user.ID, user.Email, true); err != nil {
2022-01-02 08:12:35 -05:00
log.Error("Unable to activate email for user: %-v with email: %s: %v", user, user.Email, err)
ctx.ServerError("ActivateUserEmail", err)
return
}
log.Trace("User activated: %s", user.Name)
if err := updateSession(ctx, nil, map[string]any{
[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 e3d6622a63da9c33eed1e3d102cf28a92ff653d6) (cherry picked from commit fef1a6dac5e25579e42d40209c4cfc06879948b9) (cherry picked from commit b0c5165145fa52f2f7bbec1f50b308bdf1d20ef3) (cherry picked from commit 7ad51b9f8d0647eecacd258f6ee26155da3872e1) (cherry picked from commit 64f053f3834e764112cde26bb0d16c5e88d6b2af) (cherry picked from commit f5e78e4c204ce50b800645d614218b6b6096eecb) Conflicts: services/auth/auth_token_test.go https://codeberg.org/forgejo/forgejo/pulls/2069 (cherry picked from commit f69fc23d4bbadf388c7857040ee0774b824e418e) (cherry picked from commit d955ab3ab02cbb7f1245a8cddec426d64d3ac500) (cherry picked from commit 9220088f902a25c4690bcabf5a40a8d02e784182) (cherry picked from commit c73ac636962c41c71814c273510146f0533264ab) (cherry picked from commit 747a176048ea93085b406429db0e25bb21912eda) Conflicts: models/user/user.go routers/web/user/setting/account.go https://codeberg.org/forgejo/forgejo/pulls/2295
2023-11-22 11:26:21 -05:00
"uid": user.ID,
}); err != nil {
2022-01-02 08:12:35 -05:00
log.Error("Unable to regenerate session for user: %-v with email: %s: %v", user, user.Email, err)
ctx.ServerError("ActivateUserEmail", err)
return
}
if err := resetLocale(ctx, user); err != nil {
ctx.ServerError("resetLocale", err)
return
}
if err := user_service.UpdateUser(ctx, user, &user_service.UpdateOptions{SetLastLogin: true}); err != nil {
ctx.ServerError("UpdateUser", err)
return
}
2022-01-02 08:12:35 -05:00
ctx.Flash.Success(ctx.Tr("auth.account_activated"))
if redirectTo := ctx.GetSiteCookie("redirect_to"); len(redirectTo) > 0 {
middleware.DeleteRedirectToCookie(ctx.Resp)
ctx.RedirectToFirst(redirectTo)
return
}
2022-01-02 08:12:35 -05:00
ctx.Redirect(setting.AppSubURL + "/")
}
// ActivateEmail render the activate email page
func ActivateEmail(ctx *context.Context) {
code := ctx.FormString("code")
emailStr := ctx.FormString("email")
// Verify code.
if email := user_model.VerifyActiveEmailCode(ctx, code, emailStr); email != nil {
if err := user_model.ActivateEmail(ctx, email); err != nil {
2022-01-02 08:12:35 -05:00
ctx.ServerError("ActivateEmail", err)
}
log.Trace("Email activated: %s", email.Email)
ctx.Flash.Success(ctx.Tr("settings.add_email_success"))
if u, err := user_model.GetUserByID(ctx, email.UID); err != nil {
2022-01-02 08:12:35 -05:00
log.Warn("GetUserByID: %d", email.UID)
} else {
2022-01-02 08:12:35 -05:00
// Allow user to validate more emails
_ = ctx.Cache.Delete("MailResendLimit_" + u.LowerName)
}
}
// FIXME: e-mail verification does not require the user to be logged in,
// so this could be redirecting to the login page.
// Should users be logged in automatically here? (consider 2FA requirements, etc.)
ctx.Redirect(setting.AppSubURL + "/user/settings/account")
}
func updateSession(ctx *context.Context, deletes []string, updates map[string]any) error {
if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil {
return fmt.Errorf("regenerate session: %w", err)
}
sess := ctx.Session
sessID := sess.ID()
for _, k := range deletes {
if err := sess.Delete(k); err != nil {
return fmt.Errorf("delete %v in session[%s]: %w", k, sessID, err)
}
}
for k, v := range updates {
if err := sess.Set(k, v); err != nil {
return fmt.Errorf("set %v in session[%s]: %w", k, sessID, err)
}
}
if err := sess.Release(); err != nil {
return fmt.Errorf("store session[%s]: %w", sessID, err)
}
return nil
}