Files
Gogs/internal/route/user/setting.go

672 lines
17 KiB
Go
Raw Normal View History

2014-03-10 16:54:52 +08:00
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package user
import (
2017-04-06 00:14:30 -04:00
"bytes"
"encoding/base64"
"fmt"
2017-04-06 00:14:30 -04:00
"html/template"
"image/png"
2014-11-21 10:58:08 -05:00
"io/ioutil"
2014-08-25 21:07:08 +03:00
"strings"
2017-04-06 00:14:30 -04:00
"github.com/pquerna/otp"
"github.com/pquerna/otp/totp"
"github.com/unknwon/com"
log "unknwon.dev/clog/v2"
2014-03-10 20:48:58 -04:00
"gogs.io/gogs/internal/auth"
"gogs.io/gogs/internal/conf"
"gogs.io/gogs/internal/context"
"gogs.io/gogs/internal/cryptoutil"
"gogs.io/gogs/internal/db"
"gogs.io/gogs/internal/db/errors"
2020-02-25 00:35:35 +08:00
"gogs.io/gogs/internal/email"
"gogs.io/gogs/internal/form"
"gogs.io/gogs/internal/tool"
2014-03-10 16:54:52 +08:00
)
2014-06-22 23:11:12 -04:00
const (
2017-04-06 00:14:30 -04:00
SETTINGS_PROFILE = "user/settings/profile"
SETTINGS_AVATAR = "user/settings/avatar"
SETTINGS_PASSWORD = "user/settings/password"
SETTINGS_EMAILS = "user/settings/email"
SETTINGS_SSH_KEYS = "user/settings/sshkeys"
SETTINGS_SECURITY = "user/settings/security"
SETTINGS_TWO_FACTOR_ENABLE = "user/settings/two_factor_enable"
SETTINGS_TWO_FACTOR_RECOVERY_CODES = "user/settings/two_factor_recovery_codes"
SETTINGS_REPOSITORIES = "user/settings/repositories"
SETTINGS_ORGANIZATIONS = "user/settings/organizations"
SETTINGS_APPLICATIONS = "user/settings/applications"
SETTINGS_DELETE = "user/settings/delete"
NOTIFICATION = "user/notification"
2014-06-22 23:11:12 -04:00
)
func Settings(c *context.Context) {
2017-04-07 00:49:30 -04:00
c.Title("settings.profile")
c.PageIs("SettingsProfile")
c.Data["origin_name"] = c.User.Name
c.Data["name"] = c.User.Name
c.Data["full_name"] = c.User.FullName
c.Data["email"] = c.User.Email
c.Data["website"] = c.User.Website
c.Data["location"] = c.User.Location
c.Success(SETTINGS_PROFILE)
2014-04-10 16:36:50 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsPost(c *context.Context, f form.UpdateProfile) {
c.Title("settings.profile")
c.PageIs("SettingsProfile")
c.Data["origin_name"] = c.User.Name
2017-04-07 00:49:30 -04:00
if c.HasError() {
c.Success(SETTINGS_PROFILE)
return
}
// Non-local users are not allowed to change their username
if c.User.IsLocal() {
// Check if username characters have been changed
if c.User.LowerName != strings.ToLower(f.Name) {
if err := db.ChangeUserName(c.User, f.Name); err != nil {
2017-04-07 00:49:30 -04:00
c.FormErr("Name")
var msg string
switch {
case db.IsErrUserAlreadyExist(err):
2017-04-07 00:49:30 -04:00
msg = c.Tr("form.username_been_taken")
case db.IsErrNameNotAllowed(err):
msg = c.Tr("user.form.name_not_allowed", err.(db.ErrNameNotAllowed).Value())
2017-04-07 00:49:30 -04:00
default:
c.Error(err, "change user name")
2017-04-07 00:49:30 -04:00
return
}
c.RenderWithErr(msg, SETTINGS_PROFILE, &f)
return
2014-07-26 00:24:27 -04:00
}
2015-12-11 18:52:28 -05:00
2017-04-07 00:49:30 -04:00
log.Trace("Username changed: %s -> %s", c.User.Name, f.Name)
}
2015-12-11 18:52:28 -05:00
2017-04-07 00:49:30 -04:00
// In case it's just a case change
c.User.Name = f.Name
c.User.LowerName = strings.ToLower(f.Name)
2015-12-11 18:52:28 -05:00
}
2017-04-07 00:49:30 -04:00
c.User.FullName = f.FullName
c.User.Email = f.Email
c.User.Website = f.Website
c.User.Location = f.Location
if err := db.UpdateUser(c.User); err != nil {
if db.IsErrEmailAlreadyUsed(err) {
msg := c.Tr("form.email_been_used")
c.RenderWithErr(msg, SETTINGS_PROFILE, &f)
return
}
c.Errorf(err, "update user")
return
}
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.update_profile_success"))
c.RedirectSubpath("/user/settings")
2014-03-10 16:54:52 +08:00
}
// FIXME: limit upload size
func UpdateAvatarSetting(c *context.Context, f form.Avatar, ctxUser *db.User) error {
ctxUser.UseCustomAvatar = f.Source == form.AVATAR_LOCAL
if len(f.Gravatar) > 0 {
ctxUser.Avatar = cryptoutil.MD5(f.Gravatar)
ctxUser.AvatarEmail = f.Gravatar
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
2016-08-07 19:27:38 +02:00
}
2014-11-21 12:51:36 -05:00
if f.Avatar != nil && f.Avatar.Filename != "" {
2017-04-07 00:49:30 -04:00
r, err := f.Avatar.Open()
2014-11-21 10:58:08 -05:00
if err != nil {
return fmt.Errorf("open avatar reader: %v", err)
2014-11-21 10:58:08 -05:00
}
defer func() {
_ = r.Close()
}()
2014-11-21 10:58:08 -05:00
2017-04-07 00:49:30 -04:00
data, err := ioutil.ReadAll(r)
2014-11-21 10:58:08 -05:00
if err != nil {
return fmt.Errorf("read avatar content: %v", err)
2014-11-21 10:58:08 -05:00
}
if !tool.IsImageFile(data) {
2017-04-07 00:49:30 -04:00
return errors.New(c.Tr("settings.uploaded_avatar_not_a_image"))
2014-11-21 10:58:08 -05:00
}
if err = ctxUser.UploadAvatar(data); err != nil {
return fmt.Errorf("upload avatar: %v", err)
2014-11-21 10:58:08 -05:00
}
2014-11-22 10:22:53 -05:00
} else {
// No avatar is uploaded but setting has been changed to enable,
// generate a random one when needed.
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
2016-08-07 19:27:38 +02:00
if ctxUser.UseCustomAvatar && !com.IsFile(ctxUser.CustomAvatarPath()) {
if err := ctxUser.GenerateRandomAvatar(); err != nil {
log.Error("generate random avatar [%d]: %v", ctxUser.ID, err)
}
2014-11-22 10:22:53 -05:00
}
2014-11-21 10:58:08 -05:00
}
2014-11-22 10:22:53 -05:00
if err := db.UpdateUser(ctxUser); err != nil {
return fmt.Errorf("update user: %v", err)
}
return nil
}
2017-04-07 00:49:30 -04:00
func SettingsAvatar(c *context.Context) {
c.Title("settings.avatar")
c.PageIs("SettingsAvatar")
c.Success(SETTINGS_AVATAR)
Add support for federated avatars (#3320) * Add support for federated avatars Fixes #3105 Removes avatar fetching duplication code Adds an "Enable Federated Avatar" checkbox in user settings (defaults to unchecked) Moves avatar settings all in the same form, making local and remote avatars mutually exclusive Renames UploadAvatarForm to AvatarForm as it's not anymore only for uploading * Run gofmt on all modified files * Move Avatar form in its own page * Add go-libravatar dependency to vendor/ dir Hopefully helps with accepting the contribution. See also #3214 * Revert "Add go-libravatar dependency to vendor/ dir" This reverts commit a8cb93ae640bbb90f7d25012fc257bda9fae9b82. * Make federated avatar setting a global configuration Removes the per-user setting * Move avatar handling back to base tool, disable federated avatar in offline mode * Format, handle error * Properly set fallback host * Use unsupported github.com mirror for importing go-libravatar * Remove comment showing life exists outside of github.com ... pity, but contribution would not be accepted otherwise * Use Combo for Get and Post methods over /avatar * FEDERATED_AVATAR -> ENABLE_FEDERATED_AVATAR * Fix persistance of federated avatar lookup checkbox at install time * Federated Avatars -> Enable Federated Avatars * Use len(string) == 0 instead of string == "" * Move import line where it belong See https://github.com/Unknwon/go-code-convention/blob/master/en-US/import_packages.md Pity the import url is still the unofficial one, but oh well... * Save a line (and waste much more expensive time) * Remove redundant parens * Remove an empty line * Remove empty lines * Reorder lines to make diff smaller * Remove another newline Unknwon review got me start a fight against newlines * Move DISABLE_GRAVATAR and ENABLE_FEDERATED_AVATAR after OFFLINE_MODE On re-reading the diff I figured what Unknwon meant here: https://github.com/gogits/gogs/pull/3320/files#r73741106 * Remove newlines that weren't there before my intervention
2016-08-07 19:27:38 +02:00
}
2017-04-07 00:49:30 -04:00
func SettingsAvatarPost(c *context.Context, f form.Avatar) {
if err := UpdateAvatarSetting(c, f, c.User); err != nil {
c.Flash.Error(err.Error())
} else {
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.update_avatar_success"))
2014-11-22 10:22:53 -05:00
}
c.RedirectSubpath("/user/settings/avatar")
2014-11-21 10:58:08 -05:00
}
2017-04-07 00:49:30 -04:00
func SettingsDeleteAvatar(c *context.Context) {
if err := c.User.DeleteAvatar(); err != nil {
c.Flash.Error(fmt.Sprintf("Failed to delete avatar: %v", err))
}
2016-03-06 17:36:30 +01:00
c.RedirectSubpath("/user/settings/avatar")
}
2017-04-07 00:49:30 -04:00
func SettingsPassword(c *context.Context) {
c.Title("settings.password")
c.PageIs("SettingsPassword")
c.Success(SETTINGS_PASSWORD)
2015-09-10 11:40:34 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsPasswordPost(c *context.Context, f form.ChangePassword) {
c.Title("settings.password")
c.PageIs("SettingsPassword")
2015-09-10 11:40:34 -04:00
2017-04-07 00:49:30 -04:00
if c.HasError() {
c.Success(SETTINGS_PASSWORD)
return
}
2017-04-07 00:49:30 -04:00
if !c.User.ValidatePassword(f.OldPassword) {
c.Flash.Error(c.Tr("settings.password_incorrect"))
} else if f.Password != f.Retype {
2017-04-07 00:49:30 -04:00
c.Flash.Error(c.Tr("form.password_not_match"))
2015-09-10 11:40:34 -04:00
} else {
2017-04-07 00:49:30 -04:00
c.User.Passwd = f.Password
var err error
if c.User.Salt, err = db.GetUserSalt(); err != nil {
c.Errorf(err, "get user salt")
return
}
c.User.EncodePassword()
if err := db.UpdateUser(c.User); err != nil {
c.Errorf(err, "update user")
2015-09-10 11:40:34 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.change_password_success"))
2015-09-10 11:40:34 -04:00
}
c.RedirectSubpath("/user/settings/password")
}
2017-04-07 00:49:30 -04:00
func SettingsEmails(c *context.Context) {
c.Title("settings.emails")
c.PageIs("SettingsEmails")
emails, err := db.GetEmailAddresses(c.User.ID)
if err != nil {
c.Errorf(err, "get email addresses")
return
}
2017-04-07 00:49:30 -04:00
c.Data["Emails"] = emails
2017-04-07 00:49:30 -04:00
c.Success(SETTINGS_EMAILS)
2015-09-10 11:40:34 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsEmailPost(c *context.Context, f form.AddEmail) {
c.Title("settings.emails")
c.PageIs("SettingsEmails")
// Make emailaddress primary.
2017-04-07 00:49:30 -04:00
if c.Query("_method") == "PRIMARY" {
if err := db.MakeEmailPrimary(c.UserID(), &db.EmailAddress{ID: c.QueryInt64("id")}); err != nil {
c.Errorf(err, "make email primary")
return
}
c.RedirectSubpath("/user/settings/email")
return
}
// Add Email address.
emails, err := db.GetEmailAddresses(c.User.ID)
2015-09-10 11:40:34 -04:00
if err != nil {
c.Errorf(err, "get email addresses")
2015-09-10 11:40:34 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Data["Emails"] = emails
2015-09-10 11:40:34 -04:00
2017-04-07 00:49:30 -04:00
if c.HasError() {
c.Success(SETTINGS_EMAILS)
return
}
2020-02-25 00:35:35 +08:00
emailAddr := &db.EmailAddress{
2017-04-07 00:49:30 -04:00
UID: c.User.ID,
Email: f.Email,
IsActivated: !conf.Auth.RequireEmailConfirmation,
}
2020-02-25 00:35:35 +08:00
if err := db.AddEmailAddress(emailAddr); err != nil {
if db.IsErrEmailAlreadyUsed(err) {
2017-04-07 00:49:30 -04:00
c.RenderWithErr(c.Tr("form.email_been_used"), SETTINGS_EMAILS, &f)
} else {
c.Errorf(err, "add email address")
}
return
2015-09-10 11:40:34 -04:00
}
// Send confirmation email
if conf.Auth.RequireEmailConfirmation {
2020-02-25 00:35:35 +08:00
email.SendActivateEmailMail(c.Context, db.NewMailerUser(c.User), emailAddr.Email)
2017-04-07 00:49:30 -04:00
if err := c.Cache.Put("MailResendLimit_"+c.User.LowerName, c.User.LowerName, 180); err != nil {
log.Error("Set cache 'MailResendLimit' failed: %v", err)
2015-09-10 11:40:34 -04:00
}
c.Flash.Info(c.Tr("settings.add_email_confirmation_sent", emailAddr.Email, conf.Auth.ActivateCodeLives/60))
2015-09-10 11:40:34 -04:00
} else {
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.add_email_success"))
}
c.RedirectSubpath("/user/settings/email")
2014-04-10 18:09:57 -04:00
}
2017-04-07 00:49:30 -04:00
func DeleteEmail(c *context.Context) {
if err := db.DeleteEmailAddress(&db.EmailAddress{
2017-04-07 00:49:30 -04:00
ID: c.QueryInt64("id"),
UID: c.User.ID,
2016-12-22 19:19:56 -05:00
}); err != nil {
c.Errorf(err, "delete email address")
2014-03-14 01:12:07 -04:00
return
}
2014-03-13 04:06:35 -04:00
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.email_deletion_success"))
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/email",
2015-09-10 11:40:34 -04:00
})
2014-03-13 04:06:35 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsSSHKeys(c *context.Context) {
c.Title("settings.ssh_keys")
c.PageIs("SettingsSSHKeys")
keys, err := db.ListPublicKeys(c.User.ID)
if err != nil {
c.Errorf(err, "list public keys")
2014-07-26 00:24:27 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Data["Keys"] = keys
2017-04-07 00:49:30 -04:00
c.Success(SETTINGS_SSH_KEYS)
}
2017-04-07 00:49:30 -04:00
func SettingsSSHKeysPost(c *context.Context, f form.AddSSHKey) {
c.Title("settings.ssh_keys")
c.PageIs("SettingsSSHKeys")
2014-07-26 00:24:27 -04:00
keys, err := db.ListPublicKeys(c.User.ID)
2014-07-26 00:24:27 -04:00
if err != nil {
c.Errorf(err, "list public keys")
2014-07-26 00:24:27 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Data["Keys"] = keys
2014-03-10 20:48:58 -04:00
2017-04-07 00:49:30 -04:00
if c.HasError() {
c.Success(SETTINGS_SSH_KEYS)
2015-08-20 17:11:29 +08:00
return
}
2014-03-10 20:48:58 -04:00
content, err := db.CheckPublicKeyString(f.Content)
2015-08-20 17:11:29 +08:00
if err != nil {
if db.IsErrKeyUnableVerify(err) {
2017-04-07 00:49:30 -04:00
c.Flash.Info(c.Tr("form.unable_verify_ssh_key"))
2014-03-10 21:12:49 +08:00
} else {
2017-04-07 00:49:30 -04:00
c.Flash.Error(c.Tr("form.invalid_ssh_key", err.Error()))
c.RedirectSubpath("/user/settings/ssh")
2015-08-20 17:11:29 +08:00
return
2014-03-10 21:12:49 +08:00
}
}
2014-03-10 20:48:58 -04:00
if _, err = db.AddPublicKey(c.User.ID, f.Title, content); err != nil {
2017-04-07 00:49:30 -04:00
c.Data["HasError"] = true
2015-08-20 17:11:29 +08:00
switch {
case db.IsErrKeyAlreadyExist(err):
2017-04-07 00:49:30 -04:00
c.FormErr("Content")
c.RenderWithErr(c.Tr("settings.ssh_key_been_used"), SETTINGS_SSH_KEYS, &f)
case db.IsErrKeyNameAlreadyUsed(err):
2017-04-07 00:49:30 -04:00
c.FormErr("Title")
c.RenderWithErr(c.Tr("settings.ssh_key_name_used"), SETTINGS_SSH_KEYS, &f)
2015-08-20 17:11:29 +08:00
default:
c.Errorf(err, "add public key")
2014-03-10 20:48:58 -04:00
}
2015-08-20 17:11:29 +08:00
return
}
2014-03-10 20:48:58 -04:00
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.add_key_success", f.Title))
c.RedirectSubpath("/user/settings/ssh")
2015-08-20 17:11:29 +08:00
}
2014-05-05 16:21:43 -04:00
2017-04-07 00:49:30 -04:00
func DeleteSSHKey(c *context.Context) {
if err := db.DeletePublicKey(c.User, c.QueryInt64("id")); err != nil {
2017-04-07 00:49:30 -04:00
c.Flash.Error("DeletePublicKey: " + err.Error())
2015-08-20 17:11:29 +08:00
} else {
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.ssh_key_deletion_success"))
2014-03-10 16:54:52 +08:00
}
2014-03-10 20:48:58 -04:00
2017-04-07 00:49:30 -04:00
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/ssh",
2015-08-20 17:11:29 +08:00
})
2014-03-10 16:54:52 +08:00
}
2014-03-14 17:12:28 +08:00
2017-04-06 00:14:30 -04:00
func SettingsSecurity(c *context.Context) {
2017-04-07 00:49:30 -04:00
c.Title("settings.security")
c.PageIs("SettingsSecurity")
2017-04-06 00:14:30 -04:00
t, err := db.TwoFactors.GetByUserID(c.Req.Context(), c.UserID())
if err != nil && !db.IsErrTwoFactorNotFound(err) {
c.Errorf(err, "get two factor by user ID")
2017-04-06 00:14:30 -04:00
return
}
c.Data["TwoFactor"] = t
c.Success(SETTINGS_SECURITY)
}
func SettingsTwoFactorEnable(c *context.Context) {
if c.User.IsEnabledTwoFactor() {
c.NotFound()
return
}
2017-04-07 00:49:30 -04:00
c.Title("settings.two_factor_enable_title")
c.PageIs("SettingsSecurity")
2017-04-06 00:14:30 -04:00
var key *otp.Key
var err error
keyURL := c.Session.Get("twoFactorURL")
if keyURL != nil {
key, _ = otp.NewKeyFromURL(keyURL.(string))
}
if key == nil {
key, err = totp.Generate(totp.GenerateOpts{
Issuer: conf.App.BrandName,
2017-04-06 00:14:30 -04:00
AccountName: c.User.Email,
})
if err != nil {
c.Errorf(err, "generate TOTP")
2017-04-06 00:14:30 -04:00
return
}
}
c.Data["TwoFactorSecret"] = key.Secret()
img, err := key.Image(240, 240)
if err != nil {
c.Errorf(err, "generate image")
2017-04-06 00:14:30 -04:00
return
}
var buf bytes.Buffer
if err = png.Encode(&buf, img); err != nil {
c.Errorf(err, "encode image")
2017-04-06 00:14:30 -04:00
return
}
c.Data["QRCode"] = template.URL("data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes()))
_ = c.Session.Set("twoFactorSecret", c.Data["TwoFactorSecret"])
_ = c.Session.Set("twoFactorURL", key.String())
2017-04-06 00:14:30 -04:00
c.Success(SETTINGS_TWO_FACTOR_ENABLE)
}
func SettingsTwoFactorEnablePost(c *context.Context) {
secret, ok := c.Session.Get("twoFactorSecret").(string)
if !ok {
c.NotFound()
return
}
if !totp.Validate(c.Query("passcode"), secret) {
c.Flash.Error(c.Tr("settings.two_factor_invalid_passcode"))
c.RedirectSubpath("/user/settings/security/two_factor_enable")
2017-04-06 00:14:30 -04:00
return
}
if err := db.TwoFactors.Create(c.Req.Context(), c.UserID(), conf.Security.SecretKey, secret); err != nil {
2017-04-06 00:14:30 -04:00
c.Flash.Error(c.Tr("settings.two_factor_enable_error", err))
c.RedirectSubpath("/user/settings/security/two_factor_enable")
2017-04-06 00:14:30 -04:00
return
}
_ = c.Session.Delete("twoFactorSecret")
_ = c.Session.Delete("twoFactorURL")
2017-04-06 00:14:30 -04:00
c.Flash.Success(c.Tr("settings.two_factor_enable_success"))
c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
2017-04-06 00:14:30 -04:00
}
func SettingsTwoFactorRecoveryCodes(c *context.Context) {
if !c.User.IsEnabledTwoFactor() {
c.NotFound()
return
}
2017-04-07 00:49:30 -04:00
c.Title("settings.two_factor_recovery_codes_title")
c.PageIs("SettingsSecurity")
2017-04-06 00:14:30 -04:00
recoveryCodes, err := db.GetRecoveryCodesByUserID(c.UserID())
2017-04-06 00:14:30 -04:00
if err != nil {
c.Errorf(err, "get recovery codes by user ID")
2017-04-06 00:14:30 -04:00
return
}
c.Data["RecoveryCodes"] = recoveryCodes
c.Success(SETTINGS_TWO_FACTOR_RECOVERY_CODES)
}
func SettingsTwoFactorRecoveryCodesPost(c *context.Context) {
if !c.User.IsEnabledTwoFactor() {
c.NotFound()
return
}
if err := db.RegenerateRecoveryCodes(c.UserID()); err != nil {
2017-04-06 00:14:30 -04:00
c.Flash.Error(c.Tr("settings.two_factor_regenerate_recovery_codes_error", err))
} else {
c.Flash.Success(c.Tr("settings.two_factor_regenerate_recovery_codes_success"))
}
c.RedirectSubpath("/user/settings/security/two_factor_recovery_codes")
2017-04-06 00:14:30 -04:00
}
func SettingsTwoFactorDisable(c *context.Context) {
if !c.User.IsEnabledTwoFactor() {
c.NotFound()
return
}
if err := db.DeleteTwoFactor(c.UserID()); err != nil {
c.Errorf(err, "delete two factor")
2017-04-06 00:14:30 -04:00
return
}
c.Flash.Success(c.Tr("settings.two_factor_disable_success"))
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/security",
2017-04-06 00:14:30 -04:00
})
}
2017-04-07 00:49:30 -04:00
func SettingsRepos(c *context.Context) {
c.Title("settings.repos")
c.PageIs("SettingsRepositories")
2014-11-12 06:48:50 -05:00
repos, err := db.GetUserAndCollaborativeRepositories(c.User.ID)
2014-11-12 06:48:50 -05:00
if err != nil {
c.Errorf(err, "get user and collaborative repositories")
2014-11-12 06:48:50 -05:00
return
}
if err = db.RepositoryList(repos).LoadAttributes(); err != nil {
c.Errorf(err, "load attributes")
2017-04-07 00:49:30 -04:00
return
}
c.Data["Repos"] = repos
2014-11-12 06:48:50 -05:00
2017-04-07 00:49:30 -04:00
c.Success(SETTINGS_REPOSITORIES)
2014-11-12 06:48:50 -05:00
}
2017-04-07 00:49:30 -04:00
func SettingsLeaveRepo(c *context.Context) {
repo, err := db.GetRepositoryByID(c.QueryInt64("id"))
2017-04-05 09:27:42 -04:00
if err != nil {
c.NotFoundOrError(err, "get repository by ID")
2017-04-05 09:27:42 -04:00
return
}
2017-04-07 00:49:30 -04:00
if err = repo.DeleteCollaboration(c.User.ID); err != nil {
c.Errorf(err, "delete collaboration")
2017-04-05 09:27:42 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.repos.leave_success", repo.FullName()))
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/repositories",
2017-04-07 00:49:30 -04:00
})
2017-04-05 09:27:42 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsOrganizations(c *context.Context) {
c.Title("settings.orgs")
c.PageIs("SettingsOrganizations")
orgs, err := db.GetOrgsByUserID(c.User.ID, true)
2017-04-05 09:27:42 -04:00
if err != nil {
c.Errorf(err, "get organizations by user ID")
2017-04-07 00:49:30 -04:00
return
}
c.Data["Orgs"] = orgs
c.Success(SETTINGS_ORGANIZATIONS)
}
func SettingsLeaveOrganization(c *context.Context) {
if err := db.RemoveOrgUser(c.QueryInt64("id"), c.User.ID); err != nil {
if db.IsErrLastOrgOwner(err) {
2017-04-07 00:49:30 -04:00
c.Flash.Error(c.Tr("form.last_org_owner"))
2017-04-05 09:27:42 -04:00
} else {
c.Errorf(err, "remove organization user")
2017-04-05 09:27:42 -04:00
return
}
}
2017-04-07 00:49:30 -04:00
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/organizations",
2017-04-05 09:27:42 -04:00
})
}
2017-04-07 00:49:30 -04:00
func SettingsApplications(c *context.Context) {
c.Title("settings.applications")
c.PageIs("SettingsApplications")
2017-04-05 09:27:42 -04:00
tokens, err := db.AccessTokens.List(c.Req.Context(), c.User.ID)
2017-04-07 00:49:30 -04:00
if err != nil {
c.Errorf(err, "list access tokens")
2017-04-05 09:27:42 -04:00
return
}
2017-04-07 00:49:30 -04:00
c.Data["Tokens"] = tokens
2017-04-05 09:27:42 -04:00
2017-04-07 00:49:30 -04:00
c.Success(SETTINGS_APPLICATIONS)
2017-04-05 09:27:42 -04:00
}
2017-04-07 00:49:30 -04:00
func SettingsApplicationsPost(c *context.Context, f form.NewAccessToken) {
c.Title("settings.applications")
c.PageIs("SettingsApplications")
2014-11-12 06:48:50 -05:00
2017-04-07 00:49:30 -04:00
if c.HasError() {
tokens, err := db.AccessTokens.List(c.Req.Context(), c.User.ID)
2015-08-20 17:11:29 +08:00
if err != nil {
c.Errorf(err, "list access tokens")
2015-08-20 17:11:29 +08:00
return
}
2017-04-07 00:49:30 -04:00
c.Data["Tokens"] = tokens
c.Success(SETTINGS_APPLICATIONS)
2015-08-19 03:36:16 +08:00
return
}
2014-11-12 06:48:50 -05:00
t, err := db.AccessTokens.Create(c.Req.Context(), c.User.ID, f.Name)
if err != nil {
if db.IsErrAccessTokenAlreadyExist(err) {
c.Flash.Error(c.Tr("settings.token_name_exists"))
c.RedirectSubpath("/user/settings/applications")
} else {
c.Errorf(err, "new access token")
}
2015-08-19 03:36:16 +08:00
return
}
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.generate_token_succees"))
c.Flash.Info(t.Sha1)
c.RedirectSubpath("/user/settings/applications")
2014-11-12 06:48:50 -05:00
}
2017-04-07 00:49:30 -04:00
func SettingsDeleteApplication(c *context.Context) {
if err := db.AccessTokens.DeleteByID(c.Req.Context(), c.User.ID, c.QueryInt64("id")); err != nil {
2017-04-07 00:49:30 -04:00
c.Flash.Error("DeleteAccessTokenByID: " + err.Error())
2015-08-19 03:36:16 +08:00
} else {
2017-04-07 00:49:30 -04:00
c.Flash.Success(c.Tr("settings.delete_token_success"))
2015-08-19 03:36:16 +08:00
}
2017-04-07 00:49:30 -04:00
c.JSONSuccess(map[string]interface{}{
"redirect": conf.Server.Subpath + "/user/settings/applications",
2015-08-19 03:36:16 +08:00
})
}
2017-04-07 00:49:30 -04:00
func SettingsDelete(c *context.Context) {
c.Title("settings.delete")
c.PageIs("SettingsDelete")
2014-07-26 00:24:27 -04:00
2017-04-07 00:49:30 -04:00
if c.Req.Method == "POST" {
if _, err := db.Users.Authenticate(c.Req.Context(), c.User.Name, c.Query("password"), c.User.LoginSource); err != nil {
if auth.IsErrBadCredentials(err) {
2017-04-07 00:49:30 -04:00
c.RenderWithErr(c.Tr("form.enterred_invalid_password"), SETTINGS_DELETE, nil)
} else {
c.Errorf(err, "authenticate user")
}
return
}
if err := db.DeleteUser(c.User); err != nil {
switch {
case db.IsErrUserOwnRepos(err):
2017-04-07 00:49:30 -04:00
c.Flash.Error(c.Tr("form.still_own_repo"))
c.Redirect(conf.Server.Subpath + "/user/settings/delete")
case db.IsErrUserHasOrgs(err):
2017-04-07 00:49:30 -04:00
c.Flash.Error(c.Tr("form.still_has_org"))
c.Redirect(conf.Server.Subpath + "/user/settings/delete")
2014-07-26 00:24:27 -04:00
default:
c.Errorf(err, "delete user")
2014-07-26 00:24:27 -04:00
}
} else {
2017-04-07 00:49:30 -04:00
log.Trace("Account deleted: %s", c.User.Name)
c.Redirect(conf.Server.Subpath + "/")
2014-07-26 00:24:27 -04:00
}
2014-08-14 14:12:21 +08:00
return
2014-07-26 00:24:27 -04:00
}
2017-04-07 00:49:30 -04:00
c.Success(SETTINGS_DELETE)
2014-03-14 17:12:28 +08:00
}